Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
47.16% covered (danger)
47.16%
890 / 1887
14.71% covered (danger)
14.71%
5 / 34
CRAP
0.00% covered (danger)
0.00%
0 / 1
AppController
47.08% covered (danger)
47.08%
887 / 1884
14.71% covered (danger)
14.71%
5 / 34
55754.53
0.00% covered (danger)
0.00%
0 / 1
 processSGF
98.11% covered (success)
98.11%
52 / 53
0.00% covered (danger)
0.00%
0 / 1
15
 xFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 yFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getInitialPositionEnd
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 getInitialPosition
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
6
 getDeletedSets
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 startPageUpdate
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
 deleteUnusedStatuses
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
72
 saveSolvedNumber
78.12% covered (warning)
78.12%
25 / 32
0.00% covered (danger)
0.00%
0 / 1
13.51
 resetUserElos
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 handleContribution
52.94% covered (warning)
52.94%
9 / 17
0.00% covered (danger)
0.00%
0 / 1
2.42
 getAllTags
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
7
 encrypt
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 checkPictureLarge
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 checkPicture
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 saveDanSolveCondition
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 updateSprintCondition
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
4.00
 updateGoldenCondition
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
3.00
 setPotionCondition
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 updateGems
3.85% covered (danger)
3.85%
4 / 104
0.00% covered (danger)
0.00%
0 / 1
2183.48
 checkProblemNumberAchievements
42.39% covered (danger)
42.39%
39 / 92
0.00% covered (danger)
0.00%
0 / 1
166.38
 checkDanSolveAchievements
46.82% covered (danger)
46.82%
81 / 173
0.00% covered (danger)
0.00%
0 / 1
545.62
 checkForLocked
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 checkNoErrorAchievements
50.77% covered (warning)
50.77%
33 / 65
0.00% covered (danger)
0.00%
0 / 1
51.48
 checkTimeModeAchievements
35.40% covered (danger)
35.40%
40 / 113
0.00% covered (danger)
0.00%
0 / 1
2273.83
 checkRatingAchievements
54.44% covered (warning)
54.44%
49 / 90
0.00% covered (danger)
0.00%
0 / 1
95.92
 checkLevelAchievements
72.22% covered (warning)
72.22%
65 / 90
0.00% covered (danger)
0.00%
0 / 1
42.63
 checkSetCompletedAchievements
19.72% covered (danger)
19.72%
14 / 71
0.00% covered (danger)
0.00%
0 / 1
166.54
 setAchievementSpecial
0.00% covered (danger)
0.00%
0 / 184
0.00% covered (danger)
0.00%
0 / 1
4160
 checkSetAchievements
18.10% covered (danger)
18.10%
40 / 221
0.00% covered (danger)
0.00%
0 / 1
2533.09
 updateXP
60.00% covered (warning)
60.00%
6 / 10
0.00% covered (danger)
0.00%
0 / 1
3.58
 handleSearchSettings
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 signIn
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 beforeFilter
85.40% covered (warning)
85.40%
275 / 322
0.00% covered (danger)
0.00%
0 / 1
78.14
 afterFilter
n/a
0 / 0
n/a
0 / 0
1
1<?php
2
3App::uses('Auth', 'Utility');
4App::uses('TsumegoFilters', 'Utility');
5App::uses('TimeMode', 'Utility');
6
7class AppController extends Controller {
8    public $viewClass = 'App';
9
10    public $components = [
11        'Session',
12        //'DebugKit.Toolbar',
13        'Flash',
14        'PlayResultProcessor'
15    ];
16
17    public static function processSGF($sgf) {
18        $aw = strpos($sgf, 'AW');
19        $ab = strpos($sgf, 'AB');
20        $boardSizePos = strpos($sgf, 'SZ');
21        $boardSize = 19;
22        $sgfArr = str_split($sgf);
23        if ($boardSizePos !== false) {
24            $boardSize = $sgfArr[$boardSizePos + 3] . '' . $sgfArr[$boardSizePos + 4];
25        }
26        if (substr($boardSize, 1) == ']') {
27            $boardSize = substr($boardSize, 0, 1);
28        }
29
30        $black = AppController::getInitialPosition($ab, $sgfArr, 'x');
31        $white = AppController::getInitialPosition($aw, $sgfArr, 'o');
32        $stones = array_merge($black, $white);
33
34        $board = [];
35        for ($i = 0; $i < 19; $i++) {
36            $board[$i] = [];
37            for ($j = 0; $j < 19; $j++) {
38                $board[$i][$j] = '-';
39            }
40        }
41        $lowestX = 18;
42        $lowestY = 18;
43        $highestX = 0;
44        $highestY = 0;
45        $stonesCount = count($stones);
46        for ($i = 0; $i < $stonesCount; $i++) {
47            if ($stones[$i][0] < $lowestX) {
48                $lowestX = $stones[$i][0];
49            }
50            if ($stones[$i][0] > $highestX) {
51                $highestX = $stones[$i][0];
52            }
53            if ($stones[$i][1] < $lowestY) {
54                $lowestY = $stones[$i][1];
55            }
56            if ($stones[$i][1] > $highestY) {
57                $highestY = $stones[$i][1];
58            }
59        }
60        if (18 - $lowestX < $lowestX) {
61            $stones = AppController::xFlip($stones);
62        }
63        if (18 - $lowestY < $lowestY) {
64            $stones = AppController::yFlip($stones);
65        }
66        $highestX = 0;
67        $highestY = 0;
68        $stonesCount = count($stones);
69        for ($i = 0; $i < $stonesCount; $i++) {
70            if ($stones[$i][0] > $highestX) {
71                $highestX = $stones[$i][0];
72            }
73            if ($stones[$i][1] > $highestY) {
74                $highestY = $stones[$i][1];
75            }
76            $board[$stones[$i][0]][$stones[$i][1]] = $stones[$i][2];
77        }
78        $tInfo = [];
79        $tInfo[0] = $highestX;
80        $tInfo[1] = $highestY;
81        $arr = [];
82        $arr[0] = $board;
83        $arr[1] = $stones;
84        $arr[2] = $tInfo;
85        $arr[3] = $boardSize;
86
87        return $arr;
88    }
89
90    public static function xFlip($stones) {
91        $stonesCount = count($stones);
92        for ($i = 0; $i < $stonesCount; $i++) {
93            $stones[$i][0] = 18 - $stones[$i][0];
94        }
95
96        return $stones;
97    }
98
99    public static function yFlip($stones) {
100        $stonesCount = count($stones);
101        for ($i = 0; $i < $stonesCount; $i++) {
102            $stones[$i][1] = 18 - $stones[$i][1];
103        }
104
105        return $stones;
106    }
107
108    public static function getInitialPositionEnd($pos, $sgfArr) {
109        $endCondition = 0;
110        $currentPos1 = $pos + 2;
111        $currentPos2 = $pos + 5;
112        while ($sgfArr[$currentPos1] == '[' && $sgfArr[$currentPos2] == ']') {
113            $endCondition = $currentPos2;
114            $currentPos1 += 4;
115            $currentPos2 += 4;
116        }
117
118        return $endCondition;
119    }
120
121    public static function getInitialPosition($pos, $sgfArr, $color) {
122        $arr = [];
123        $end = AppController::getInitialPositionEnd($pos, $sgfArr);
124        for ($i = $pos + 2; $i < $end; $i++) {
125            if ($sgfArr[$i] != '[' && $sgfArr[$i] != ']') {
126                array_push($arr, strtolower($sgfArr[$i]));
127            }
128        }
129        $alphabet = array_flip(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']);
130        $xy = true;
131        $arr2 = [];
132        $c = 0;
133        $arrCount = count($arr);
134        for ($i = 0; $i < $arrCount; $i++) {
135            $arr[$i] = $alphabet[$arr[$i]];
136            if ($xy) {
137                $arr2[$c] = [];
138                $arr2[$c][0] = $arr[$i];
139            } else {
140                $arr2[$c][1] = $arr[$i];
141                $arr2[$c][2] = $color;
142                $c++;
143            }
144            $xy = !$xy;
145        }
146
147        return $arr2;
148    }
149
150    protected function getDeletedSets() {
151        $dSets = [];
152        $de = $this->Set->find('all', ['conditions' => ['public' => -1]]);
153        if (!$de) {
154            $de = [];
155        }
156        foreach ($de as $item) {
157            $dSets[] = $item['Set']['id'];
158        }
159
160        return $dSets;
161    }
162
163    /**
164     * @return void
165     */
166    public static function startPageUpdate() {
167        $str = '';
168        $latest = ClassRegistry::init('AchievementStatus')->find('all', ['limit' => 7, 'order' => 'created DESC']);
169        if (!$latest) {
170            $latest = [];
171        }
172        $latestCount = count($latest);
173        for ($i = 0; $i < $latestCount; $i++) {
174            $a = ClassRegistry::init('Achievement')->findById($latest[$i]['AchievementStatus']['achievement_id']);
175            $u = ClassRegistry::init('User')->findById($latest[$i]['AchievementStatus']['user_id']);
176            if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
177                $startPageUser = AppController::checkPicture($u);
178            } else {
179                $startPageUser = $u['User']['name'];
180            }
181            $latest[$i]['AchievementStatus']['name'] = $a['Achievement']['name'];
182            $latest[$i]['AchievementStatus']['color'] = $a['Achievement']['color'];
183            $latest[$i]['AchievementStatus']['image'] = $a['Achievement']['image'];
184            $latest[$i]['AchievementStatus']['user'] = $startPageUser;
185            $str .= '<div class="quote1"><div class="quote1a"><a href="/achievements/view/' . $a['Achievement']['id'] . '"><img src="/img/' . $a['Achievement']['image'] . '.png" width="34px"></a></div>';
186            $str .= '<div class="quote1b">Achievement gained by ' . $startPageUser . ':<br><div class=""><b>' . $a['Achievement']['name'] . '</b></div></div></div>';
187        }
188        file_put_contents('mainPageAjax.txt', $str);
189    }
190
191    public static function deleteUnusedStatuses(int $uid): void {
192        $s = ClassRegistry::init('Set')->find('all', [
193            'conditions' => [
194                'OR' => [
195                    ['public' => 1],
196                    ['public' => 0],
197                ],
198            ],
199        ]) ?: [];
200        $ids = [];
201        $sCount = count($s);
202        for ($i = 0; $i < $sCount; $i++) {
203            $tSet = TsumegoUtil::collectTsumegosFromSet($s[$i]['Set']['id']);
204            foreach ($tSet as $item) {
205                $ids[] = $item['Tsumego']['id'];
206            }
207        }
208        $ut = ClassRegistry::init('TsumegoStatus')->find('all', [
209            'conditions' => [
210                'user_id' => $uid,
211                'NOT' => [
212                    'tsumego_id' => $ids,
213                ],
214            ],
215        ]);
216        if (!$ut) {
217            $ut = [];
218        }
219        $utCount = count($ut);
220        for ($i = 0; $i < $utCount; $i++) {
221            $test1 = ClassRegistry::init('Tsumego')->findById($ut[$i]['TsumegoStatus']['tsumego_id']);
222            $test2 = ClassRegistry::init('SetConnection')->find('first', ['conditions' => ['tsumego_id' => $test1['Tsumego']['id']]]);
223            if (!$test2) {
224                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
225
226                continue;
227            }
228            $test3 = ClassRegistry::init('Set')->find('first', [
229                'id' => $test2['SetConnection']['set_id'],
230                'OR' => [
231                    ['public' => 1],
232                    ['public' => 0],
233                ],
234            ]);
235            if ($test3 == null) {
236                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
237            }
238        }
239    }
240
241    protected function saveSolvedNumber($uid) {
242        $this->loadModel('User');
243        $this->loadModel('TsumegoStatus');
244        $this->loadModel('Set');
245        $this->loadModel('SetConnection');
246
247        $solvedUts2 = 0;
248        $tsumegos = $this->SetConnection->find('all');
249        if (!$tsumegos) {
250            $tsumegos = [];
251        }
252        $uts = $this->TsumegoStatus->find('all', ['order' => 'updated DESC', 'conditions' => ['user_id' => $uid]]);
253        if (!$uts) {
254            $uts = [];
255        }
256        $setKeys = [];
257        $setArray = $this->Set->find('all', ['conditions' => ['public' => 1]]);
258        if (!$setArray) {
259            $setArray = [];
260        }
261
262        $setArrayCount = count($setArray);
263        for ($i = 0; $i < $setArrayCount; $i++) {
264            $setKeys[$setArray[$i]['Set']['id']] = $setArray[$i]['Set']['id'];
265        }
266
267        $scs = [];
268        $tsumegosCount = count($tsumegos);
269        for ($j = 0; $j < $tsumegosCount; $j++) {
270            if (!isset($scs[$tsumegos[$j]['SetConnection']['tsumego_id']])) {
271                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']] = 1;
272            } else {
273                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']]++;
274            }
275        }
276        $utsCount = count($uts);
277        for ($j = 0; $j < $utsCount; $j++) {
278            if ($uts[$j]['TsumegoStatus']['status'] == 'S' || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C') {
279                if (isset($scs[$uts[$j]['TsumegoStatus']['tsumego_id']])) {
280                    $solvedUts2 += $scs[$uts[$j]['TsumegoStatus']['tsumego_id']];
281                }
282            }
283        }
284        Auth::getUser()['solved'] = $solvedUts2;
285        Auth::saveUser();
286
287        return $solvedUts2;
288    }
289
290    /**
291     * @return void
292     */
293    protected function resetUserElos() {
294        $this->loadModel('User');
295
296        $u = $this->User->find('all', [
297            'conditions' => [
298                'id >=' => 15000,
299                'id <=' => 19000,
300            ],
301        ]);
302        if (!$u) {
303            $u = [];
304        }
305
306        $uCount = count($u);
307        for ($i = 0; $i < $uCount; $i++) {
308            $u[$i]['User']['rating'] = 900;
309            $u[$i]['User']['solved2'] = 0;
310            $this->User->save($u[$i]);
311        }
312    }
313
314    /**
315     * @param int $uid User ID
316     * @param string $action Action type
317     *
318     * @return void
319     */
320    public static function handleContribution($uid, $action) {
321        $uc = ClassRegistry::init('UserContribution')->find('first', ['conditions' => ['user_id' => $uid]]);
322        if ($uc == null) {
323            $uc = [];
324            $uc['UserContribution']['user_id'] = $uid;
325            $uc['UserContribution']['added_tag'] = 0;
326            $uc['UserContribution']['created_tag'] = 0;
327            $uc['UserContribution']['made_proposal'] = 0;
328            $uc['UserContribution']['reviewed'] = 0;
329            $uc['UserContribution']['score'] = 0;
330            ClassRegistry::init('UserContribution')->create();
331        }
332        $uc['UserContribution'][$action] += 1;
333        $uc['UserContribution']['score']
334        = $uc['UserContribution']['added_tag']
335        + $uc['UserContribution']['created_tag'] * 3
336        + $uc['UserContribution']['made_proposal'] * 5
337        + $uc['UserContribution']['reviewed'] * 2;
338        ClassRegistry::init('UserContribution')->save($uc);
339    }
340
341    public static function getAllTags($not) {
342        $a = [];
343        $notApproved = ClassRegistry::init('TagName')->find('all', ['conditions' => ['approved' => 0]]);
344        if (!$notApproved) {
345            $notApproved = [];
346        }
347        $notCount = count($not);
348        for ($i = 0; $i < $notCount; $i++) {
349            array_push($a, $not[$i]['Tag']['tag_name_id']);
350        }
351        $notApprovedCount = count($notApproved);
352        for ($i = 0; $i < $notApprovedCount; $i++) {
353            array_push($a, $notApproved[$i]['TagName']['id']);
354        }
355        $tn = ClassRegistry::init('TagName')->find('all', [
356            'conditions' => [
357                'NOT' => ['id' => $a],
358            ],
359        ]);
360        if (!$tn) {
361            $tn = [];
362        }
363        $sorted = [];
364        $keys = [];
365        $tnCount = count($tn);
366        for ($i = 0; $i < $tnCount; $i++) {
367            array_push($sorted, $tn[$i]['TagName']['name']);
368            $keys[$tn[$i]['TagName']['name']] = $tn[$i];
369        }
370        sort($sorted);
371        $s2 = [];
372        $sortedCount = count($sorted);
373        for ($i = 0; $i < $sortedCount; $i++) {
374            array_push($s2, $keys[$sorted[$i]]);
375        }
376
377        return $s2;
378    }
379
380    public static function encrypt($str = null) {
381        $secret_key = 'my_simple_secret_keyx';
382        $secret_iv = 'my_simple_secret_ivx';
383        $encrypt_method = 'AES-256-CBC';
384        $key = hash('sha256', $secret_key);
385        $iv = substr(hash('sha256', $secret_iv), 0, 16);
386
387        return base64_encode(openssl_encrypt($str, $encrypt_method, $key, 0, $iv));
388    }
389
390    protected function checkPictureLarge($u) {
391        if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
392            return '<img class="google-profile-image-large" src="/img/google/' . $u['User']['picture'] . '">' . substr($u['User']['name'], 3);
393        }
394
395        return $u['User']['name'];
396    }
397    public static function checkPicture($user) {
398        if (substr($user['name'], 0, 3) == 'g__' && $user['external_id'] != null) {
399            return '<img class="google-profile-image" src="/img/google/' . $user['picture'] . '">' . substr($user['name'], 3);
400        }
401
402        return $user['name'];
403    }
404
405    public static function saveDanSolveCondition($solvedTsumegoRank, $tId): void {
406        if ($solvedTsumegoRank == '1d' || $solvedTsumegoRank == '2d' || $solvedTsumegoRank == '3d' || $solvedTsumegoRank == '4d' || $solvedTsumegoRank == '5d') {
407            $danSolveCategory = 'danSolve' . $solvedTsumegoRank;
408            $danSolveCondition = ClassRegistry::init('AchievementCondition')->find('first', [
409                'order' => 'value DESC',
410                'conditions' => [
411                    'user_id' => Auth::getUserID(),
412                    'category' => $danSolveCategory,
413                ],
414            ]);
415            if (!$danSolveCondition) {
416                $danSolveCondition = [];
417                $danSolveCondition['AchievementCondition']['value'] = 0;
418                ClassRegistry::init('AchievementCondition')->create();
419            }
420            $danSolveCondition['AchievementCondition']['category'] = $danSolveCategory;
421            $danSolveCondition['AchievementCondition']['user_id'] = Auth::getUserID();
422            $danSolveCondition['AchievementCondition']['set_id'] = $tId;
423            $danSolveCondition['AchievementCondition']['value']++;
424
425            ClassRegistry::init('AchievementCondition')->save($danSolveCondition);
426        }
427    }
428
429    public static function updateSprintCondition(bool $trigger = false): void {
430        if (Auth::isLoggedIn()) {
431            $sprintCondition = ClassRegistry::init('AchievementCondition')->find('first', [
432                'order' => 'value DESC',
433                'conditions' => [
434                    'user_id' => Auth::getUserID(),
435                    'category' => 'sprint',
436                ],
437            ]);
438            if (!$sprintCondition) {
439                $sprintCondition = [];
440                $sprintCondition['AchievementCondition']['value'] = 0;
441                ClassRegistry::init('AchievementCondition')->create();
442            }
443            $sprintCondition['AchievementCondition']['category'] = 'sprint';
444            $sprintCondition['AchievementCondition']['user_id'] = Auth::getUserID();
445            if ($trigger) {
446                $sprintCondition['AchievementCondition']['value']++;
447            } else {
448                $sprintCondition['AchievementCondition']['value'] = 0;
449            }
450            ClassRegistry::init('AchievementCondition')->save($sprintCondition);
451        }
452    }
453
454    public static function updateGoldenCondition(bool $trigger = false): void {
455        $goldenCondition = ClassRegistry::init('AchievementCondition')->find('first', [
456            'order' => 'value DESC',
457            'conditions' => [
458                'user_id' => Auth::getUserID(),
459                'category' => 'golden',
460            ],
461        ]);
462        if (!$goldenCondition) {
463            $goldenCondition = [];
464            $goldenCondition['AchievementCondition']['value'] = 0;
465            ClassRegistry::init('AchievementCondition')->create();
466        }
467        $goldenCondition['AchievementCondition']['category'] = 'golden';
468        $goldenCondition['AchievementCondition']['user_id'] = Auth::getUserID();
469        if ($trigger) {
470            $goldenCondition['AchievementCondition']['value']++;
471        } else {
472            $goldenCondition['AchievementCondition']['value'] = 0;
473        }
474        ClassRegistry::init('AchievementCondition')->save($goldenCondition);
475    }
476
477    public static function setPotionCondition(): void {
478        $potionCondition = ClassRegistry::init('AchievementCondition')->find('first', [
479            'order' => 'value DESC',
480            'conditions' => [
481                'user_id' => Auth::getUserID(),
482                'category' => 'potion',
483            ],
484        ]);
485        if (!$potionCondition) {
486            $potionCondition = [];
487            ClassRegistry::init('AchievementCondition')->create();
488        }
489        $potionCondition['AchievementCondition']['category'] = 'potion';
490        $potionCondition['AchievementCondition']['user_id'] = Auth::getUserID();
491        $potionCondition['AchievementCondition']['value'] = 1;
492        ClassRegistry::init('AchievementCondition')->save($potionCondition);
493    }
494
495    public static function updateGems(string $rank): void {
496        $datex = new DateTime('today');
497        $dateGem = ClassRegistry::init('DayRecord')->find('first', ['conditions' => ['date' => $datex->format('Y-m-d')]]);
498        if ($dateGem != null) {
499            $gems = explode('-', $dateGem['DayRecord']['gems']);
500            $gemValue = '';
501            $gemValue2 = '';
502            $gemValue3 = '';
503            $condition1 = 500;
504            $condition2 = 200;
505            $condition3 = 5;
506            $found1 = false;
507            $found2 = false;
508            $found3 = false;
509            if ($rank == '15k' || $rank == '14k' || $rank == '13k' || $rank == '12k' || $rank == '11k' || $rank == '10k') {
510                if ($gems[0] == 0) {
511                    $gemValue = '15k';
512                } elseif ($gems[0] == 1) {
513                    $gemValue = '12k';
514                } elseif ($gems[0] == 2) {
515                    $gemValue = '10k';
516                }
517                if ($rank == $gemValue) {
518                    $dateGem['DayRecord']['gemCounter1']++;
519                    if ($dateGem['DayRecord']['gemCounter1'] == $condition1) {
520                        $found1 = true;
521                    }
522                }
523            } elseif ($rank == '9k' || $rank == '8k' || $rank == '7k' || $rank == '6k' || $rank == '5k' || $rank == '4k' || $rank == '3k' || $rank == '2k' || $rank == '1k') {
524                if ($gems[1] == 0) {
525                    $gemValue = '9k';
526                    $gemValue2 = 'x';
527                    $gemValue3 = 'y';
528                } elseif ($gems[1] == 1) {
529                    $gemValue = '6k';
530                    $gemValue2 = '5k';
531                    $gemValue3 = '4k';
532                } elseif ($gems[1] == 2) {
533                    $gemValue = 'x';
534                    $gemValue2 = '2k';
535                    $gemValue3 = '1k';
536                }
537                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
538                    $dateGem['DayRecord']['gemCounter2']++;
539                    if ($dateGem['DayRecord']['gemCounter2'] == $condition2) {
540                        $found2 = true;
541                    }
542                }
543            } elseif ($rank == '1d' || $rank == '2d' || $rank == '3d' || $rank == '4d' || $rank == '5d' || $rank == '6d' || $rank == '7d') {
544                if ($gems[2] == 0) {
545                    $gemValue = '1d';
546                    $gemValue2 = '2d';
547                    $gemValue3 = '3d';
548                } elseif ($gems[2] == 1) {
549                    $gemValue = '2d';
550                    $gemValue2 = '3d';
551                    $gemValue3 = '4d';
552                } elseif ($gems[2] == 2) {
553                    $gemValue = '5d';
554                    $gemValue2 = '6d';
555                    $gemValue3 = '7d';
556                }
557                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
558                    $dateGem['DayRecord']['gemCounter3']++;
559                    if ($dateGem['DayRecord']['gemCounter3'] == $condition3) {
560                        $found3 = true;
561                    }
562                }
563            }
564            if ($found1) {
565                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
566                    'order' => 'value DESC',
567                    'conditions' => [
568                        'user_id' => Auth::getUserID(),
569                        'category' => 'emerald',
570                    ],
571                ]);
572                if ($aCondition == null) {
573                    $aCondition = [];
574                    $aCondition['AchievementCondition']['category'] = 'emerald';
575                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
576                    $aCondition['AchievementCondition']['value'] = 1;
577                    ClassRegistry::init('AchievementCondition')->save($aCondition);
578                } else {
579                    $dateGem['DayRecord']['gemCounter1']--;
580                }
581            } elseif ($found2) {
582                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
583                    'order' => 'value DESC',
584                    'conditions' => [
585                        'user_id' => Auth::getUserID(),
586                        'category' => 'sapphire',
587                    ],
588                ]);
589                if ($aCondition == null) {
590                    $aCondition = [];
591                    $aCondition['AchievementCondition']['category'] = 'sapphire';
592                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
593                    $aCondition['AchievementCondition']['value'] = 1;
594                    ClassRegistry::init('AchievementCondition')->save($aCondition);
595                } else {
596                    $dateGem['DayRecord']['gemCounter2']--;
597                }
598            } elseif ($found3) {
599                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
600                    'order' => 'value DESC',
601                    'conditions' => [
602                        'user_id' => Auth::getUserID(),
603                        'category' => 'ruby',
604                    ],
605                ]);
606                if ($aCondition == null) {
607                    $aCondition = [];
608                    $aCondition['AchievementCondition']['category'] = 'ruby';
609                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
610                    $aCondition['AchievementCondition']['value'] = 1;
611                    ClassRegistry::init('AchievementCondition')->save($aCondition);
612                } else {
613                    $dateGem['DayRecord']['gemCounter3']--;
614                }
615            }
616        }
617        ClassRegistry::init('DayRecord')->save($dateGem);
618    }
619
620    public static function checkProblemNumberAchievements() {
621        if (!Auth::isLoggedIn()) {
622            return;
623        }
624
625        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
626        if (!$buffer) {
627            $buffer = [];
628        }
629        $existingAs = [];
630        $bufferCount = count($buffer);
631        for ($i = 0; $i < $bufferCount; $i++) {
632            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
633        }
634        $as = [];
635        $as['AchievementStatus']['user_id'] = Auth::getUserID();
636        $updated = [];
637
638        $achievementId = 1;
639        $solvedCount = Auth::getUser()['solved'];
640        if ($solvedCount >= 1000 && !isset($existingAs[$achievementId])) {
641            $as['AchievementStatus']['achievement_id'] = $achievementId;
642            ClassRegistry::init('AchievementStatus')->create();
643            ClassRegistry::init('AchievementStatus')->save($as);
644            array_push($updated, $achievementId);
645        }
646        $achievementId = 2;
647        if ($solvedCount >= 2000 && !isset($existingAs[$achievementId])) {
648            $as['AchievementStatus']['achievement_id'] = $achievementId;
649            ClassRegistry::init('AchievementStatus')->create();
650            ClassRegistry::init('AchievementStatus')->save($as);
651            array_push($updated, $achievementId);
652        }
653        $achievementId = 3;
654        if ($solvedCount >= 3000 && !isset($existingAs[$achievementId])) {
655            $as['AchievementStatus']['achievement_id'] = $achievementId;
656            ClassRegistry::init('AchievementStatus')->create();
657            ClassRegistry::init('AchievementStatus')->save($as);
658            array_push($updated, $achievementId);
659        }
660        $achievementId = 4;
661        if ($solvedCount >= 4000 && !isset($existingAs[$achievementId])) {
662            $as['AchievementStatus']['achievement_id'] = $achievementId;
663            ClassRegistry::init('AchievementStatus')->create();
664            ClassRegistry::init('AchievementStatus')->save($as);
665            array_push($updated, $achievementId);
666        }
667        $achievementId = 5;
668        if ($solvedCount >= 5000 && !isset($existingAs[$achievementId])) {
669            $as['AchievementStatus']['achievement_id'] = $achievementId;
670            ClassRegistry::init('AchievementStatus')->create();
671            ClassRegistry::init('AchievementStatus')->save($as);
672            array_push($updated, $achievementId);
673        }
674        $achievementId = 6;
675        if ($solvedCount >= 6000 && !isset($existingAs[$achievementId])) {
676            $as['AchievementStatus']['achievement_id'] = $achievementId;
677            ClassRegistry::init('AchievementStatus')->create();
678            ClassRegistry::init('AchievementStatus')->save($as);
679            array_push($updated, $achievementId);
680        }
681        $achievementId = 7;
682        if ($solvedCount >= 7000 && !isset($existingAs[$achievementId])) {
683            $as['AchievementStatus']['achievement_id'] = $achievementId;
684            ClassRegistry::init('AchievementStatus')->create();
685            ClassRegistry::init('AchievementStatus')->save($as);
686            array_push($updated, $achievementId);
687        }
688        $achievementId = 8;
689        if ($solvedCount >= 8000 && !isset($existingAs[$achievementId])) {
690            $as['AchievementStatus']['achievement_id'] = $achievementId;
691            ClassRegistry::init('AchievementStatus')->create();
692            ClassRegistry::init('AchievementStatus')->save($as);
693            array_push($updated, $achievementId);
694        }
695        $achievementId = 9;
696        if ($solvedCount >= 9000 && !isset($existingAs[$achievementId])) {
697            $as['AchievementStatus']['achievement_id'] = $achievementId;
698            ClassRegistry::init('AchievementStatus')->create();
699            ClassRegistry::init('AchievementStatus')->save($as);
700            array_push($updated, $achievementId);
701        }
702        $achievementId = 10;
703        if ($solvedCount >= 10000 && !isset($existingAs[$achievementId])) {
704            $as['AchievementStatus']['achievement_id'] = $achievementId;
705            ClassRegistry::init('AchievementStatus')->create();
706            ClassRegistry::init('AchievementStatus')->save($as);
707            array_push($updated, $achievementId);
708        }
709        //uotd achievement
710        $achievementId = 11;
711        if (!isset($existingAs[$achievementId])) {
712            $condition = ClassRegistry::init('AchievementCondition')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => 'uotd']]);
713            if ($condition != null) {
714                $as['AchievementStatus']['achievement_id'] = $achievementId;
715                ClassRegistry::init('AchievementStatus')->create();
716                ClassRegistry::init('AchievementStatus')->save($as);
717                array_push($updated, $achievementId);
718            }
719        }
720
721        $updatedCount = count($updated);
722        for ($i = 0; $i < $updatedCount; $i++) {
723            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
724            $updated[$i] = [];
725            $updated[$i][0] = $a['Achievement']['name'];
726            $updated[$i][1] = $a['Achievement']['description'];
727            $updated[$i][2] = $a['Achievement']['image'];
728            $updated[$i][3] = $a['Achievement']['color'];
729            $updated[$i][4] = $a['Achievement']['xp'];
730            $updated[$i][5] = $a['Achievement']['id'];
731        }
732
733        return $updated;
734    }
735
736    public static function checkDanSolveAchievements() {
737        if (Auth::isLoggedIn()) {
738            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
739            if (!$buffer) {
740                $buffer = [];
741            }
742            $ac = ClassRegistry::init('AchievementCondition')->find('all', [
743                'order' => 'category ASC',
744                'conditions' => [
745                    'user_id' => Auth::getUserID(),
746                    'OR' => [
747                        ['category' => 'danSolve1d'],
748                        ['category' => 'danSolve2d'],
749                        ['category' => 'danSolve3d'],
750                        ['category' => 'danSolve4d'],
751                        ['category' => 'danSolve5d'],
752                        ['category' => 'emerald'],
753                        ['category' => 'sapphire'],
754                        ['category' => 'ruby'],
755                        ['category' => 'sprint'],
756                        ['category' => 'golden'],
757                        ['category' => 'potion'],
758                    ],
759                ],
760            ]);
761            if (!$ac) {
762                $ac = [];
763            }
764            $ac1 = [];
765            $acCount = count($ac);
766            for ($i = 0; $i < $acCount; $i++) {
767                if ($ac[$i]['AchievementCondition']['category'] == 'danSolve1d') {
768                    $ac1['1d'] = $ac[$i]['AchievementCondition']['value'];
769                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve2d') {
770                    $ac1['2d'] = $ac[$i]['AchievementCondition']['value'];
771                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve3d') {
772                    $ac1['3d'] = $ac[$i]['AchievementCondition']['value'];
773                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve4d') {
774                    $ac1['4d'] = $ac[$i]['AchievementCondition']['value'];
775                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve5d') {
776                    $ac1['5d'] = $ac[$i]['AchievementCondition']['value'];
777                } elseif ($ac[$i]['AchievementCondition']['category'] == 'emerald') {
778                    $ac1['emerald'] = $ac[$i]['AchievementCondition']['value'];
779                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sapphire') {
780                    $ac1['sapphire'] = $ac[$i]['AchievementCondition']['value'];
781                } elseif ($ac[$i]['AchievementCondition']['category'] == 'ruby') {
782                    $ac1['ruby'] = $ac[$i]['AchievementCondition']['value'];
783                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sprint') {
784                    $ac1['sprint'] = $ac[$i]['AchievementCondition']['value'];
785                } elseif ($ac[$i]['AchievementCondition']['category'] == 'golden') {
786                    $ac1['golden'] = $ac[$i]['AchievementCondition']['value'];
787                } elseif ($ac[$i]['AchievementCondition']['category'] == 'potion') {
788                    $ac1['potion'] = $ac[$i]['AchievementCondition']['value'];
789                }
790            }
791
792            $existingAs = [];
793            $bufferCount = count($buffer);
794            for ($i = 0; $i < $bufferCount; $i++) {
795                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
796            }
797            $as = [];
798            $as['AchievementStatus']['user_id'] = Auth::getUserID();
799            $updated = [];
800            $achievementId = 101;
801            if ($ac1['1d'] > 0 && !isset($existingAs[$achievementId])) {
802                $as['AchievementStatus']['achievement_id'] = $achievementId;
803                ClassRegistry::init('AchievementStatus')->create();
804                ClassRegistry::init('AchievementStatus')->save($as);
805                array_push($updated, $achievementId);
806            }
807            $achievementId = 102;
808            if ($ac1['2d'] > 0 && !isset($existingAs[$achievementId])) {
809                $as['AchievementStatus']['achievement_id'] = $achievementId;
810                ClassRegistry::init('AchievementStatus')->create();
811                ClassRegistry::init('AchievementStatus')->save($as);
812                array_push($updated, $achievementId);
813            }
814            $achievementId = 103;
815            if ($ac1['3d'] > 0 && !isset($existingAs[$achievementId])) {
816                $as['AchievementStatus']['achievement_id'] = $achievementId;
817                ClassRegistry::init('AchievementStatus')->create();
818                ClassRegistry::init('AchievementStatus')->save($as);
819                array_push($updated, $achievementId);
820            }
821            $achievementId = 104;
822            if ($ac1['4d'] > 0 && !isset($existingAs[$achievementId])) {
823                $as['AchievementStatus']['achievement_id'] = $achievementId;
824                ClassRegistry::init('AchievementStatus')->create();
825                ClassRegistry::init('AchievementStatus')->save($as);
826                array_push($updated, $achievementId);
827            }
828            $achievementId = 105;
829            if ($ac1['5d'] > 0 && !isset($existingAs[$achievementId])) {
830                $as['AchievementStatus']['achievement_id'] = $achievementId;
831                ClassRegistry::init('AchievementStatus')->create();
832                ClassRegistry::init('AchievementStatus')->save($as);
833                array_push($updated, $achievementId);
834            }
835            $achievementId = 106;
836            if ($ac1['1d'] >= 10 && !isset($existingAs[$achievementId])) {
837                $as['AchievementStatus']['achievement_id'] = $achievementId;
838                ClassRegistry::init('AchievementStatus')->create();
839                ClassRegistry::init('AchievementStatus')->save($as);
840                array_push($updated, $achievementId);
841            }
842            $achievementId = 107;
843            if ($ac1['2d'] >= 10 && !isset($existingAs[$achievementId])) {
844                $as['AchievementStatus']['achievement_id'] = $achievementId;
845                ClassRegistry::init('AchievementStatus')->create();
846                ClassRegistry::init('AchievementStatus')->save($as);
847                array_push($updated, $achievementId);
848            }
849            $achievementId = 108;
850            if ($ac1['3d'] >= 10 && !isset($existingAs[$achievementId])) {
851                $as['AchievementStatus']['achievement_id'] = $achievementId;
852                ClassRegistry::init('AchievementStatus')->create();
853                ClassRegistry::init('AchievementStatus')->save($as);
854                array_push($updated, $achievementId);
855            }
856            $achievementId = 109;
857            if ($ac1['4d'] >= 10 && !isset($existingAs[$achievementId])) {
858                $as['AchievementStatus']['achievement_id'] = $achievementId;
859                ClassRegistry::init('AchievementStatus')->create();
860                ClassRegistry::init('AchievementStatus')->save($as);
861                array_push($updated, $achievementId);
862            }
863            $achievementId = 110;
864            if ($ac1['5d'] >= 10 && !isset($existingAs[$achievementId])) {
865                $as['AchievementStatus']['achievement_id'] = $achievementId;
866                ClassRegistry::init('AchievementStatus')->create();
867                ClassRegistry::init('AchievementStatus')->save($as);
868                array_push($updated, $achievementId);
869            }
870            $achievementId = 111;
871            if (isset($ac1['emerald'])) {
872                if ($ac1['emerald'] == 1 && !isset($existingAs[$achievementId])) {
873                    $as['AchievementStatus']['achievement_id'] = $achievementId;
874                    ClassRegistry::init('AchievementStatus')->create();
875                    ClassRegistry::init('AchievementStatus')->save($as);
876                    array_push($updated, $achievementId);
877                }
878            }
879            $achievementId = 112;
880            if (isset($ac1['sapphire'])) {
881                if ($ac1['sapphire'] == 1 && !isset($existingAs[$achievementId])) {
882                    $as['AchievementStatus']['achievement_id'] = $achievementId;
883                    ClassRegistry::init('AchievementStatus')->create();
884                    ClassRegistry::init('AchievementStatus')->save($as);
885                    array_push($updated, $achievementId);
886                }
887            }
888            $achievementId = 113;
889            if (isset($ac1['ruby'])) {
890                if ($ac1['ruby'] == 1 && !isset($existingAs[$achievementId])) {
891                    $as['AchievementStatus']['achievement_id'] = $achievementId;
892                    ClassRegistry::init('AchievementStatus')->create();
893                    ClassRegistry::init('AchievementStatus')->save($as);
894                    array_push($updated, $achievementId);
895                }
896            }
897            $achievementId = 114;
898            if (!isset($existingAs[$achievementId]) && isset($existingAs[111]) && isset($existingAs[112]) && isset($existingAs[113])) {
899                $as['AchievementStatus']['achievement_id'] = $achievementId;
900                ClassRegistry::init('AchievementStatus')->create();
901                ClassRegistry::init('AchievementStatus')->save($as);
902                array_push($updated, $achievementId);
903            }
904            $achievementId = 96;
905            if (!isset($existingAs[$achievementId]) && $ac1['sprint'] >= 30) {
906                $as['AchievementStatus']['achievement_id'] = $achievementId;
907                ClassRegistry::init('AchievementStatus')->create();
908                ClassRegistry::init('AchievementStatus')->save($as);
909                array_push($updated, $achievementId);
910            }
911            $achievementId = 97;
912            if (!isset($existingAs[$achievementId]) && $ac1['golden'] >= 10) {
913                $as['AchievementStatus']['achievement_id'] = $achievementId;
914                ClassRegistry::init('AchievementStatus')->create();
915                ClassRegistry::init('AchievementStatus')->save($as);
916                array_push($updated, $achievementId);
917            }
918            $achievementId = 98;
919            if (!isset($existingAs[$achievementId]) && $ac1['potion'] >= 1) {
920                $as['AchievementStatus']['achievement_id'] = $achievementId;
921                ClassRegistry::init('AchievementStatus')->create();
922                ClassRegistry::init('AchievementStatus')->save($as);
923                array_push($updated, $achievementId);
924            }
925            $updatedCount = count($updated);
926            for ($i = 0; $i < $updatedCount; $i++) {
927                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
928                $updated[$i] = [];
929                $updated[$i][0] = $a['Achievement']['name'];
930                $updated[$i][1] = $a['Achievement']['description'];
931                $updated[$i][2] = $a['Achievement']['image'];
932                $updated[$i][3] = $a['Achievement']['color'];
933                $updated[$i][4] = $a['Achievement']['xp'];
934                $updated[$i][5] = $a['Achievement']['id'];
935            }
936
937            return $updated;
938        }
939    }
940
941    protected function checkForLocked($t, $setsWithPremium) {
942        $scCheck = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $t['Tsumego']['id']]]);
943        if ($scCheck && in_array($scCheck['SetConnection']['set_id'], $setsWithPremium) && !Auth::hasPremium()) {
944            $t['Tsumego']['locked'] = true;
945        } else {
946            $t['Tsumego']['locked'] = false;
947        }
948
949        return $t;
950    }
951    public static function checkNoErrorAchievements() {
952        if (Auth::isLoggedIn()) {
953
954            $ac = ClassRegistry::init('AchievementCondition')->find('first', [
955                'order' => 'value DESC',
956                'conditions' => [
957                    'user_id' => Auth::getUserID(),
958                    'category' => 'err',
959                ],
960            ]);
961
962            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
963            if (!$buffer) {
964                $buffer = [];
965            }
966            $existingAs = [];
967            $bufferCount = count($buffer);
968            for ($i = 0; $i < $bufferCount; $i++) {
969                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
970            }
971            $as = [];
972            $as['AchievementStatus']['user_id'] = Auth::getUserID();
973            $updated = [];
974
975            $achievementId = 53;
976            if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
977                $as['AchievementStatus']['achievement_id'] = $achievementId;
978                ClassRegistry::init('AchievementStatus')->create();
979                ClassRegistry::init('AchievementStatus')->save($as);
980                array_push($updated, $achievementId);
981            }
982            $achievementId = 54;
983            if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
984                $as['AchievementStatus']['achievement_id'] = $achievementId;
985                ClassRegistry::init('AchievementStatus')->create();
986                ClassRegistry::init('AchievementStatus')->save($as);
987                array_push($updated, $achievementId);
988            }
989            $achievementId = 55;
990            if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
991                $as['AchievementStatus']['achievement_id'] = $achievementId;
992                ClassRegistry::init('AchievementStatus')->create();
993                ClassRegistry::init('AchievementStatus')->save($as);
994                array_push($updated, $achievementId);
995            }
996            $achievementId = 56;
997            if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
998                $as['AchievementStatus']['achievement_id'] = $achievementId;
999                ClassRegistry::init('AchievementStatus')->create();
1000                ClassRegistry::init('AchievementStatus')->save($as);
1001                array_push($updated, $achievementId);
1002            }
1003            $achievementId = 57;
1004            if ($ac['AchievementCondition']['value'] >= 100 && !isset($existingAs[$achievementId])) {
1005                $as['AchievementStatus']['achievement_id'] = $achievementId;
1006                ClassRegistry::init('AchievementStatus')->create();
1007                ClassRegistry::init('AchievementStatus')->save($as);
1008                array_push($updated, $achievementId);
1009            }
1010            $achievementId = 58;
1011            if ($ac['AchievementCondition']['value'] >= 200 && !isset($existingAs[$achievementId])) {
1012                $as['AchievementStatus']['achievement_id'] = $achievementId;
1013                ClassRegistry::init('AchievementStatus')->create();
1014                ClassRegistry::init('AchievementStatus')->save($as);
1015                array_push($updated, $achievementId);
1016            }
1017            $updatedCount = count($updated);
1018            for ($i = 0; $i < $updatedCount; $i++) {
1019                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1020                $updated[$i] = [];
1021                $updated[$i][0] = $a['Achievement']['name'];
1022                $updated[$i][1] = $a['Achievement']['description'];
1023                $updated[$i][2] = $a['Achievement']['image'];
1024                $updated[$i][3] = $a['Achievement']['color'];
1025                $updated[$i][4] = $a['Achievement']['xp'];
1026                $updated[$i][5] = $a['Achievement']['id'];
1027            }
1028
1029            return $updated;
1030        }
1031    }
1032
1033    protected function checkTimeModeAchievements() {
1034        $this->loadModel('Achievement');
1035        $this->loadModel('AchievementStatus');
1036        $this->loadModel('TimeModeSession');
1037
1038        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1039        if (!$buffer) {
1040            $buffer = [];
1041        }
1042        $existingAs = [];
1043        $bufferCount = count($buffer);
1044        for ($i = 0; $i < $bufferCount; $i++) {
1045            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1046        }
1047        $as = [];
1048        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1049        $updated = [];
1050
1051        $rBlitz = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_BLITZ, 'user_id' => Auth::getUserID()]]);
1052        if (!$rBlitz) {
1053            $rBlitz = [];
1054        }
1055        $rFast = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_FAST_SPEED, 'user_id' => Auth::getUserID()]]);
1056        if (!$rFast) {
1057            $rFast = [];
1058        }
1059        $rSlow = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_SLOW_SPEED, 'user_id' => Auth::getUserID()]]);
1060        if (!$rSlow) {
1061            $rSlow = [];
1062        }
1063        $r = $this->TimeModeSession->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1064        if (!$r) {
1065            $r = [];
1066        }
1067
1068        $timeModeAchievements = [];
1069        for ($i = 70; $i <= 91; $i++) {
1070            $timeModeAchievements[$i] = false;
1071        }
1072        $rCount = count($r);
1073        for ($i = 0; $i < $rCount; $i++) {
1074            if ($r[$i]['TimeModeSession']['status'] == 's') {
1075                if ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k') {
1076                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1077                        $timeModeAchievements[70] = true;
1078                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1079                        $timeModeAchievements[76] = true;
1080                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1081                        $timeModeAchievements[82] = true;
1082                    }
1083                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k') {
1084                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1085                        $timeModeAchievements[71] = true;
1086                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1087                        $timeModeAchievements[77] = true;
1088                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1089                        $timeModeAchievements[83] = true;
1090                    }
1091                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k') {
1092                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1093                        $timeModeAchievements[72] = true;
1094                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1095                        $timeModeAchievements[78] = true;
1096                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1097                        $timeModeAchievements[84] = true;
1098                    }
1099                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k') {
1100                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1101                        $timeModeAchievements[73] = true;
1102                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1103                        $timeModeAchievements[79] = true;
1104                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1105                        $timeModeAchievements[85] = true;
1106                    }
1107                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k') {
1108                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1109                        $timeModeAchievements[74] = true;
1110                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1111                        $timeModeAchievements[80] = true;
1112                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1113                        $timeModeAchievements[86] = true;
1114                    }
1115                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d') {
1116                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1117                        $timeModeAchievements[75] = true;
1118                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1119                        $timeModeAchievements[81] = true;
1120                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1121                        $timeModeAchievements[87] = true;
1122                    }
1123                }
1124            }
1125            if ($r[$i]['TimeModeSession']['points'] >= 850
1126            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1127            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1128            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d')) {
1129                $timeModeAchievements[91] = true;
1130            }
1131            if ($r[$i]['TimeModeSession']['points'] >= 875
1132            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1133            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1134            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k')) {
1135                $timeModeAchievements[90] = true;
1136            }
1137            if ($r[$i]['TimeModeSession']['points'] >= 900
1138            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1139            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1140            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
1141            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k')) {
1142                $timeModeAchievements[89] = true;
1143            }
1144            if ($r[$i]['TimeModeSession']['points'] >= 950
1145            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1146            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1147            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
1148            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '9k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '10k')) {
1149                $timeModeAchievements[88] = true;
1150            }
1151        }
1152        for ($i = 70; $i <= 91; $i++) {
1153            $achievementId = $i;
1154            if ($timeModeAchievements[$achievementId] == true && !isset($existingAs[$achievementId])) {
1155                $as['AchievementStatus']['achievement_id'] = $achievementId;
1156                ClassRegistry::init('AchievementStatus')->create();
1157                ClassRegistry::init('AchievementStatus')->save($as);
1158                array_push($updated, $achievementId);
1159            }
1160        }
1161        $updatedCount = count($updated);
1162        for ($i = 0; $i < $updatedCount; $i++) {
1163            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1164            $updated[$i] = [];
1165            $updated[$i][0] = $a['Achievement']['name'];
1166            $updated[$i][1] = $a['Achievement']['description'];
1167            $updated[$i][2] = $a['Achievement']['image'];
1168            $updated[$i][3] = $a['Achievement']['color'];
1169            $updated[$i][4] = $a['Achievement']['xp'];
1170            $updated[$i][5] = $a['Achievement']['id'];
1171        }
1172
1173        return $updated;
1174    }
1175
1176    public static function checkRatingAchievements() {
1177        if (!Auth::isLoggedIn()) {
1178            return;
1179        }
1180
1181        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1182        if (!$buffer) {
1183            $buffer = [];
1184        }
1185        $existingAs = [];
1186        $bufferCount = count($buffer);
1187        for ($i = 0; $i < $bufferCount; $i++) {
1188            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1189        }
1190        $as = [];
1191        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1192        $updated = [];
1193
1194        $achievementId = 59;
1195        $currentElo = Auth::getUser()['rating'];
1196        if ($currentElo >= 1500 && !isset($existingAs[$achievementId])) {
1197            $as['AchievementStatus']['achievement_id'] = $achievementId;
1198            ClassRegistry::init('AchievementStatus')->create();
1199            ClassRegistry::init('AchievementStatus')->save($as);
1200            array_push($updated, $achievementId);
1201        }
1202        $achievementId = 60;
1203        if ($currentElo >= 1600 && !isset($existingAs[$achievementId])) {
1204            $as['AchievementStatus']['achievement_id'] = $achievementId;
1205            ClassRegistry::init('AchievementStatus')->create();
1206            ClassRegistry::init('AchievementStatus')->save($as);
1207            array_push($updated, $achievementId);
1208        }
1209        $achievementId = 61;
1210        if ($currentElo >= 1700 && !isset($existingAs[$achievementId])) {
1211            $as['AchievementStatus']['achievement_id'] = $achievementId;
1212            ClassRegistry::init('AchievementStatus')->create();
1213            ClassRegistry::init('AchievementStatus')->save($as);
1214            array_push($updated, $achievementId);
1215        }
1216        $achievementId = 62;
1217        if ($currentElo >= 1800 && !isset($existingAs[$achievementId])) {
1218            $as['AchievementStatus']['achievement_id'] = $achievementId;
1219            ClassRegistry::init('AchievementStatus')->create();
1220            ClassRegistry::init('AchievementStatus')->save($as);
1221            array_push($updated, $achievementId);
1222        }
1223        $achievementId = 63;
1224        if ($currentElo >= 1900 && !isset($existingAs[$achievementId])) {
1225            $as['AchievementStatus']['achievement_id'] = $achievementId;
1226            ClassRegistry::init('AchievementStatus')->create();
1227            ClassRegistry::init('AchievementStatus')->save($as);
1228            array_push($updated, $achievementId);
1229        }
1230        $achievementId = 64;
1231        if ($currentElo >= 2000 && !isset($existingAs[$achievementId])) {
1232            $as['AchievementStatus']['achievement_id'] = $achievementId;
1233            ClassRegistry::init('AchievementStatus')->create();
1234            ClassRegistry::init('AchievementStatus')->save($as);
1235            array_push($updated, $achievementId);
1236        }
1237        $achievementId = 65;
1238        if ($currentElo >= 2100 && !isset($existingAs[$achievementId])) {
1239            $as['AchievementStatus']['achievement_id'] = $achievementId;
1240            ClassRegistry::init('AchievementStatus')->create();
1241            ClassRegistry::init('AchievementStatus')->save($as);
1242            array_push($updated, $achievementId);
1243        }
1244        $achievementId = 66;
1245        if ($currentElo >= 2200 && !isset($existingAs[$achievementId])) {
1246            $as['AchievementStatus']['achievement_id'] = $achievementId;
1247            ClassRegistry::init('AchievementStatus')->create();
1248            ClassRegistry::init('AchievementStatus')->save($as);
1249            array_push($updated, $achievementId);
1250        }
1251        $achievementId = 67;
1252        if ($currentElo >= 2300 && !isset($existingAs[$achievementId])) {
1253            $as['AchievementStatus']['achievement_id'] = $achievementId;
1254            ClassRegistry::init('AchievementStatus')->create();
1255            ClassRegistry::init('AchievementStatus')->save($as);
1256            array_push($updated, $achievementId);
1257        }
1258        $achievementId = 68;
1259        if ($currentElo >= 2400 && !isset($existingAs[$achievementId])) {
1260            $as['AchievementStatus']['achievement_id'] = $achievementId;
1261            ClassRegistry::init('AchievementStatus')->create();
1262            ClassRegistry::init('AchievementStatus')->save($as);
1263            array_push($updated, $achievementId);
1264        }
1265        $achievementId = 69;
1266        if ($currentElo >= 2500 && !isset($existingAs[$achievementId])) {
1267            $as['AchievementStatus']['achievement_id'] = $achievementId;
1268            ClassRegistry::init('AchievementStatus')->create();
1269            ClassRegistry::init('AchievementStatus')->save($as);
1270            array_push($updated, $achievementId);
1271        }
1272        $updatedCount = count($updated);
1273        for ($i = 0; $i < $updatedCount; $i++) {
1274            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1275            $updated[$i] = [];
1276            $updated[$i][0] = $a['Achievement']['name'];
1277            $updated[$i][1] = $a['Achievement']['description'];
1278            $updated[$i][2] = $a['Achievement']['image'];
1279            $updated[$i][3] = $a['Achievement']['color'];
1280            $updated[$i][4] = $a['Achievement']['xp'];
1281            $updated[$i][5] = $a['Achievement']['id'];
1282        }
1283
1284        return $updated;
1285    }
1286
1287    public static function checkLevelAchievements() {
1288        if (!Auth::isLoggedIn()) {
1289            return;
1290        }
1291        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1292        if (!$buffer) {
1293            $buffer = [];
1294        }
1295        $existingAs = [];
1296        $bufferCount = count($buffer);
1297        for ($i = 0; $i < $bufferCount; $i++) {
1298            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1299        }
1300        $as = [];
1301        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1302        $updated = [];
1303
1304        $achievementId = 36;
1305        $userLevel = Auth::getUser()['level'];
1306        if ($userLevel >= 10 && !isset($existingAs[$achievementId])) {
1307            $as['AchievementStatus']['achievement_id'] = $achievementId;
1308            ClassRegistry::init('AchievementStatus')->create();
1309            ClassRegistry::init('AchievementStatus')->save($as);
1310            array_push($updated, $achievementId);
1311        }
1312        $achievementId = 37;
1313        if ($userLevel >= 20 && !isset($existingAs[$achievementId])) {
1314            $as['AchievementStatus']['achievement_id'] = $achievementId;
1315            ClassRegistry::init('AchievementStatus')->create();
1316            ClassRegistry::init('AchievementStatus')->save($as);
1317            array_push($updated, $achievementId);
1318        }
1319        $achievementId = 38;
1320        if ($userLevel >= 30 && !isset($existingAs[$achievementId])) {
1321            $as['AchievementStatus']['achievement_id'] = $achievementId;
1322            ClassRegistry::init('AchievementStatus')->create();
1323            ClassRegistry::init('AchievementStatus')->save($as);
1324            array_push($updated, $achievementId);
1325        }
1326        $achievementId = 39;
1327        if ($userLevel >= 40 && !isset($existingAs[$achievementId])) {
1328            $as['AchievementStatus']['achievement_id'] = $achievementId;
1329            ClassRegistry::init('AchievementStatus')->create();
1330            ClassRegistry::init('AchievementStatus')->save($as);
1331            array_push($updated, $achievementId);
1332        }
1333        $achievementId = 40;
1334        if ($userLevel >= 50 && !isset($existingAs[$achievementId])) {
1335            $as['AchievementStatus']['achievement_id'] = $achievementId;
1336            ClassRegistry::init('AchievementStatus')->create();
1337            ClassRegistry::init('AchievementStatus')->save($as);
1338            array_push($updated, $achievementId);
1339        }
1340        $achievementId = 41;
1341        if ($userLevel >= 60 && !isset($existingAs[$achievementId])) {
1342            $as['AchievementStatus']['achievement_id'] = $achievementId;
1343            ClassRegistry::init('AchievementStatus')->create();
1344            ClassRegistry::init('AchievementStatus')->save($as);
1345            array_push($updated, $achievementId);
1346        }
1347        $achievementId = 42;
1348        if ($userLevel >= 70 && !isset($existingAs[$achievementId])) {
1349            $as['AchievementStatus']['achievement_id'] = $achievementId;
1350            ClassRegistry::init('AchievementStatus')->create();
1351            ClassRegistry::init('AchievementStatus')->save($as);
1352            array_push($updated, $achievementId);
1353        }
1354        $achievementId = 43;
1355        if ($userLevel >= 80 && !isset($existingAs[$achievementId])) {
1356            $as['AchievementStatus']['achievement_id'] = $achievementId;
1357            ClassRegistry::init('AchievementStatus')->create();
1358            ClassRegistry::init('AchievementStatus')->save($as);
1359            array_push($updated, $achievementId);
1360        }
1361        $achievementId = 44;
1362        if ($userLevel >= 90 && !isset($existingAs[$achievementId])) {
1363            $as['AchievementStatus']['achievement_id'] = $achievementId;
1364            ClassRegistry::init('AchievementStatus')->create();
1365            ClassRegistry::init('AchievementStatus')->save($as);
1366            array_push($updated, $achievementId);
1367        }
1368        $achievementId = 45;
1369        if ($userLevel >= 100 && !isset($existingAs[$achievementId])) {
1370            $as['AchievementStatus']['achievement_id'] = $achievementId;
1371            ClassRegistry::init('AchievementStatus')->create();
1372            ClassRegistry::init('AchievementStatus')->save($as);
1373            array_push($updated, $achievementId);
1374        }
1375        $achievementId = 100;
1376        if (Auth::hasPremium() && !isset($existingAs[$achievementId])) {
1377            $as['AchievementStatus']['achievement_id'] = $achievementId;
1378            ClassRegistry::init('AchievementStatus')->create();
1379            ClassRegistry::init('AchievementStatus')->save($as);
1380            array_push($updated, $achievementId);
1381        }
1382        $updatedCount = count($updated);
1383        for ($i = 0; $i < $updatedCount; $i++) {
1384            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1385            $updated[$i] = [];
1386            $updated[$i][0] = $a['Achievement']['name'];
1387            $updated[$i][1] = $a['Achievement']['description'];
1388            $updated[$i][2] = $a['Achievement']['image'];
1389            $updated[$i][3] = $a['Achievement']['color'];
1390            $updated[$i][4] = $a['Achievement']['xp'];
1391            $updated[$i][5] = $a['Achievement']['id'];
1392        }
1393
1394        return $updated;
1395    }
1396
1397    protected function checkSetCompletedAchievements() {
1398        $this->loadModel('Set');
1399        $this->loadModel('Tsumego');
1400        $this->loadModel('Achievement');
1401        $this->loadModel('AchievementStatus');
1402        $this->loadModel('AchievementCondition');
1403
1404        $ac = ClassRegistry::init('AchievementCondition')->find('first', [
1405            'order' => 'value DESC',
1406            'conditions' => [
1407                'user_id' => Auth::getUserID(),
1408                'category' => 'set',
1409            ],
1410        ]);
1411
1412        if (!$ac) {
1413            return [];
1414        }
1415
1416        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1417        if (!$buffer) {
1418            $buffer = [];
1419        }
1420        $existingAs = [];
1421        $bufferCount = count($buffer);
1422        for ($i = 0; $i < $bufferCount; $i++) {
1423            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1424        }
1425        $as = [];
1426        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1427        $updated = [];
1428
1429        $achievementId = 47;
1430        if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
1431            $as['AchievementStatus']['achievement_id'] = $achievementId;
1432            ClassRegistry::init('AchievementStatus')->create();
1433            ClassRegistry::init('AchievementStatus')->save($as);
1434            array_push($updated, $achievementId);
1435        }
1436        $achievementId = 48;
1437        if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
1438            $as['AchievementStatus']['achievement_id'] = $achievementId;
1439            ClassRegistry::init('AchievementStatus')->create();
1440            ClassRegistry::init('AchievementStatus')->save($as);
1441            array_push($updated, $achievementId);
1442        }
1443        $achievementId = 49;
1444        if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
1445            $as['AchievementStatus']['achievement_id'] = $achievementId;
1446            ClassRegistry::init('AchievementStatus')->create();
1447            ClassRegistry::init('AchievementStatus')->save($as);
1448            array_push($updated, $achievementId);
1449        }
1450        $achievementId = 50;
1451        if ($ac['AchievementCondition']['value'] >= 40 && !isset($existingAs[$achievementId])) {
1452            $as['AchievementStatus']['achievement_id'] = $achievementId;
1453            ClassRegistry::init('AchievementStatus')->create();
1454            ClassRegistry::init('AchievementStatus')->save($as);
1455            array_push($updated, $achievementId);
1456        }
1457        $achievementId = 51;
1458        if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
1459            $as['AchievementStatus']['achievement_id'] = $achievementId;
1460            ClassRegistry::init('AchievementStatus')->create();
1461            ClassRegistry::init('AchievementStatus')->save($as);
1462            array_push($updated, $achievementId);
1463        }
1464        $achievementId = 52;
1465        if ($ac['AchievementCondition']['value'] >= 60 && !isset($existingAs[$achievementId])) {
1466            $as['AchievementStatus']['achievement_id'] = $achievementId;
1467            ClassRegistry::init('AchievementStatus')->create();
1468            ClassRegistry::init('AchievementStatus')->save($as);
1469            array_push($updated, $achievementId);
1470        }
1471        $updatedCount = count($updated);
1472        for ($i = 0; $i < $updatedCount; $i++) {
1473            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1474            $updated[$i] = [];
1475            $updated[$i][0] = $a['Achievement']['name'];
1476            $updated[$i][1] = $a['Achievement']['description'];
1477            $updated[$i][2] = $a['Achievement']['image'];
1478            $updated[$i][3] = $a['Achievement']['color'];
1479            $updated[$i][4] = $a['Achievement']['xp'];
1480            $updated[$i][5] = $a['Achievement']['id'];
1481        }
1482
1483        return $updated;
1484    }
1485
1486    protected function setAchievementSpecial($s = null) {
1487        $this->loadModel('Set');
1488        $this->loadModel('Tsumego');
1489        $this->loadModel('TsumegoStatus');
1490        $this->loadModel('Achievement');
1491        $this->loadModel('AchievementStatus');
1492        $this->loadModel('SetConnection');
1493
1494        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1495        if (!$buffer) {
1496            $buffer = [];
1497        }
1498        $existingAs = [];
1499        $bufferCount = count($buffer);
1500        for ($i = 0; $i < $bufferCount; $i++) {
1501            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1502        }
1503        $as = [];
1504        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1505        $updated = [];
1506
1507        $tsIds = [];
1508        $completed = '';
1509        if ($s == 'cc1') {
1510            $ts1 = TsumegoUtil::collectTsumegosFromSet(50);
1511            $ts2 = TsumegoUtil::collectTsumegosFromSet(52);
1512            $ts3 = TsumegoUtil::collectTsumegosFromSet(53);
1513            $ts4 = TsumegoUtil::collectTsumegosFromSet(54);
1514            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
1515            $tsCount = count($ts);
1516            for ($i = 0; $i < $tsCount; $i++) {
1517                array_push($tsIds, $ts[$i]['Tsumego']['id']);
1518            }
1519            $uts = $this->TsumegoStatus->find('all', [
1520                'conditions' => [
1521                    'user_id' => Auth::getUserID(),
1522                    'tsumego_id' => $tsIds,
1523                ],
1524            ]);
1525            if (!$uts) {
1526                $uts = [];
1527            }
1528            $counter = 0;
1529            $utsCount = count($uts);
1530            for ($j = 0; $j < $utsCount; $j++) {
1531                for ($k = 0; $k < $tsCount; $k++) {
1532                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
1533                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
1534                        $counter++;
1535                    }
1536                }
1537            }
1538            if ($counter == count($ts)) {
1539                $completed = $s;
1540            }
1541        } elseif ($s == 'cc2') {
1542            $ts1 = TsumegoUtil::collectTsumegosFromSet(41);
1543            $ts2 = TsumegoUtil::collectTsumegosFromSet(49);
1544            $ts3 = TsumegoUtil::collectTsumegosFromSet(65);
1545            $ts4 = TsumegoUtil::collectTsumegosFromSet(66);
1546            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
1547            $tsCount = count($ts);
1548            for ($i = 0; $i < $tsCount; $i++) {
1549                array_push($tsIds, $ts[$i]['Tsumego']['id']);
1550            }
1551            $uts = $this->TsumegoStatus->find('all', [
1552                'conditions' => [
1553                    'user_id' => Auth::getUserID(),
1554                    'tsumego_id' => $tsIds,
1555                ],
1556            ]);
1557            if (!$uts) {
1558                $uts = [];
1559            }
1560            $counter = 0;
1561            $utsCount = count($uts);
1562            for ($j = 0; $j < $utsCount; $j++) {
1563                for ($k = 0; $k < $tsCount; $k++) {
1564                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
1565                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
1566                        $counter++;
1567                    }
1568                }
1569            }
1570            if ($counter == count($ts)) {
1571                $completed = $s;
1572            }
1573        } elseif ($s == 'cc3') {
1574            $ts1 = TsumegoUtil::collectTsumegosFromSet(186);
1575            $ts2 = TsumegoUtil::collectTsumegosFromSet(187);
1576            $ts3 = TsumegoUtil::collectTsumegosFromSet(196);
1577            $ts4 = TsumegoUtil::collectTsumegosFromSet(203);
1578            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
1579            $tsCount = count($ts);
1580            for ($i = 0; $i < $tsCount; $i++) {
1581                array_push($tsIds, $ts[$i]['Tsumego']['id']);
1582            }
1583            $uts = $this->TsumegoStatus->find('all', [
1584                'conditions' => [
1585                    'user_id' => Auth::getUserID(),
1586                    'tsumego_id' => $tsIds,
1587                ],
1588            ]);
1589            if (!$uts) {
1590                $uts = [];
1591            }
1592            $counter = 0;
1593            $utsCount = count($uts);
1594            for ($j = 0; $j < $utsCount; $j++) {
1595                for ($k = 0; $k < $tsCount; $k++) {
1596                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
1597                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
1598                        $counter++;
1599                    }
1600                }
1601            }
1602            if ($counter == count($ts)) {
1603                $completed = $s;
1604            }
1605        } elseif ($s == '1000w1') {
1606            $ts1 = TsumegoUtil::collectTsumegosFromSet(190);
1607            $ts2 = TsumegoUtil::collectTsumegosFromSet(193);
1608            $ts3 = TsumegoUtil::collectTsumegosFromSet(198);
1609            $ts = array_merge($ts1, $ts2, $ts3);
1610            $tsCount = count($ts);
1611            for ($i = 0; $i < $tsCount; $i++) {
1612                array_push($tsIds, $ts[$i]['Tsumego']['id']);
1613            }
1614            $uts = $this->TsumegoStatus->find('all', [
1615                'conditions' => [
1616                    'user_id' => Auth::getUserID(),
1617                    'tsumego_id' => $tsIds,
1618                ],
1619            ]);
1620            if (!$uts) {
1621                $uts = [];
1622            }
1623            $counter = 0;
1624            $utsCount = count($uts);
1625            for ($j = 0; $j < $utsCount; $j++) {
1626                for ($k = 0; $k < $tsCount; $k++) {
1627                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
1628                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
1629                        $counter++;
1630                    }
1631                }
1632            }
1633            if ($counter == count($ts)) {
1634                $completed = $s;
1635            }
1636        } elseif ($s == '1000w2') {
1637            $ts = TsumegoUtil::collectTsumegosFromSet(216);
1638            $tsCount = count($ts);
1639            for ($i = 0; $i < $tsCount; $i++) {
1640                array_push($tsIds, $ts[$i]['Tsumego']['id']);
1641            }
1642            $uts = $this->TsumegoStatus->find('all', [
1643                'conditions' => [
1644                    'user_id' => Auth::getUserID(),
1645                    'tsumego_id' => $tsIds,
1646                ],
1647            ]);
1648            if (!$uts) {
1649                $uts = [];
1650            }
1651            $counter = 0;
1652            $utsCount = count($uts);
1653            for ($j = 0; $j < $utsCount; $j++) {
1654                for ($k = 0; $k < $tsCount; $k++) {
1655                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
1656                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
1657                        $counter++;
1658                    }
1659                }
1660            }
1661            if ($counter == count($ts)) {
1662                $completed = $s;
1663            }
1664        }
1665
1666        $achievementId = 92;
1667        if ($completed == 'cc1' && !isset($existingAs[$achievementId])) {
1668            $as['AchievementStatus']['achievement_id'] = $achievementId;
1669            ClassRegistry::init('AchievementStatus')->create();
1670            ClassRegistry::init('AchievementStatus')->save($as);
1671            array_push($updated, $achievementId);
1672        }
1673        $achievementId = 93;
1674        if ($completed == 'cc2' && !isset($existingAs[$achievementId])) {
1675            $as['AchievementStatus']['achievement_id'] = $achievementId;
1676            ClassRegistry::init('AchievementStatus')->create();
1677            ClassRegistry::init('AchievementStatus')->save($as);
1678            array_push($updated, $achievementId);
1679        }
1680        $achievementId = 94;
1681        if ($completed == 'cc3' && !isset($existingAs[$achievementId])) {
1682            $as['AchievementStatus']['achievement_id'] = $achievementId;
1683            ClassRegistry::init('AchievementStatus')->create();
1684            ClassRegistry::init('AchievementStatus')->save($as);
1685            array_push($updated, $achievementId);
1686        }
1687        $achievementId = 95;
1688        if ($completed == '1000w1' && !isset($existingAs[$achievementId])) {
1689            $as['AchievementStatus']['achievement_id'] = $achievementId;
1690            ClassRegistry::init('AchievementStatus')->create();
1691            ClassRegistry::init('AchievementStatus')->save($as);
1692            array_push($updated, $achievementId);
1693        }
1694        $achievementId = 115;
1695        if ($completed == '1000w2' && !isset($existingAs[$achievementId])) {
1696            $as['AchievementStatus']['achievement_id'] = $achievementId;
1697            ClassRegistry::init('AchievementStatus')->create();
1698            ClassRegistry::init('AchievementStatus')->save($as);
1699            array_push($updated, $achievementId);
1700        }
1701        $updatedCount = count($updated);
1702        for ($i = 0; $i < $updatedCount; $i++) {
1703            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1704            $updated[$i] = [];
1705            $updated[$i][0] = $a['Achievement']['name'];
1706            $updated[$i][1] = $a['Achievement']['description'];
1707            $updated[$i][2] = $a['Achievement']['image'];
1708            $updated[$i][3] = $a['Achievement']['color'];
1709            $updated[$i][4] = $a['Achievement']['xp'];
1710            $updated[$i][5] = $a['Achievement']['id'];
1711        }
1712
1713        return $updated;
1714    }
1715
1716    protected function checkSetAchievements($sid = null) {
1717        $this->loadModel('Set');
1718        $this->loadModel('Tsumego');
1719        $this->loadModel('Achievement');
1720        $this->loadModel('AchievementStatus');
1721        $this->loadModel('AchievementCondition');
1722
1723        //$tNum = count($this->Tsumego->find('all', array('conditions' => array('set_id' => $sid))));
1724        $tNum = count(TsumegoUtil::collectTsumegosFromSet($sid));
1725        $s = $this->Set->findById($sid);
1726        $acA = ClassRegistry::init('AchievementCondition')->find('first', [
1727            'order' => 'value DESC',
1728            'conditions' => [
1729                'set_id' => $sid,
1730                'user_id' => Auth::getUserID(),
1731                'category' => '%',
1732            ],
1733        ]);
1734        if (!$acA) {
1735            return [];
1736        }
1737        $acS = ClassRegistry::init('AchievementCondition')->find('first', [
1738            'order' => 'value ASC',
1739            'conditions' => [
1740                'set_id' => $sid,
1741                'user_id' => Auth::getUserID(),
1742                'category' => 's',
1743            ],
1744        ]);
1745        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1746        if (!$buffer) {
1747            $buffer = [];
1748        }
1749        $existingAs = [];
1750        $bufferCount = count($buffer);
1751        for ($i = 0; $i < $bufferCount; $i++) {
1752            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1753        }
1754        $as = [];
1755        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1756        $updated = [];
1757
1758        $achievementId = 99;
1759        if ($sid == -1 && !isset($existingAs[$achievementId])) {
1760            $as['AchievementStatus']['achievement_id'] = $achievementId;
1761            ClassRegistry::init('AchievementStatus')->create();
1762            ClassRegistry::init('AchievementStatus')->save($as);
1763            array_push($updated, $achievementId);
1764        }
1765        if ($tNum >= 100) {
1766            if ($s['Set']['difficulty'] < 1300) {
1767                $achievementId = 12;
1768                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
1769                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1770                    ClassRegistry::init('AchievementStatus')->create();
1771                    ClassRegistry::init('AchievementStatus')->save($as);
1772                    array_push($updated, $achievementId);
1773                }
1774                $achievementId = 13;
1775                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
1776                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1777                    ClassRegistry::init('AchievementStatus')->create();
1778                    ClassRegistry::init('AchievementStatus')->save($as);
1779                    array_push($updated, $achievementId);
1780                }
1781                $achievementId = 14;
1782                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
1783                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1784                    ClassRegistry::init('AchievementStatus')->create();
1785                    ClassRegistry::init('AchievementStatus')->save($as);
1786                    array_push($updated, $achievementId);
1787                }
1788                $achievementId = 24;
1789                if ($acS['AchievementCondition']['value'] < 15 && !isset($existingAs[$achievementId])) {
1790                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1791                    ClassRegistry::init('AchievementStatus')->create();
1792                    ClassRegistry::init('AchievementStatus')->save($as);
1793                    array_push($updated, $achievementId);
1794                }
1795                $achievementId = 25;
1796                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
1797                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1798                    ClassRegistry::init('AchievementStatus')->create();
1799                    ClassRegistry::init('AchievementStatus')->save($as);
1800                    array_push($updated, $achievementId);
1801                }
1802                $achievementId = 26;
1803                if ($acS['AchievementCondition']['value'] < 5 && !isset($existingAs[$achievementId])) {
1804                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1805                    ClassRegistry::init('AchievementStatus')->create();
1806                    ClassRegistry::init('AchievementStatus')->save($as);
1807                    array_push($updated, $achievementId);
1808                }
1809            } elseif ($s['Set']['difficulty'] >= 1300 && $s['Set']['difficulty'] < 1500) {
1810                $achievementId = 15;
1811                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
1812                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1813                    ClassRegistry::init('AchievementStatus')->create();
1814                    ClassRegistry::init('AchievementStatus')->save($as);
1815                    array_push($updated, $achievementId);
1816                }
1817                $achievementId = 16;
1818                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
1819                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1820                    ClassRegistry::init('AchievementStatus')->create();
1821                    ClassRegistry::init('AchievementStatus')->save($as);
1822                    array_push($updated, $achievementId);
1823                }
1824                $achievementId = 17;
1825                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
1826                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1827                    ClassRegistry::init('AchievementStatus')->create();
1828                    ClassRegistry::init('AchievementStatus')->save($as);
1829                    array_push($updated, $achievementId);
1830                }
1831                $achievementId = 27;
1832                if ($acS['AchievementCondition']['value'] < 18 && !isset($existingAs[$achievementId])) {
1833                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1834                    ClassRegistry::init('AchievementStatus')->create();
1835                    ClassRegistry::init('AchievementStatus')->save($as);
1836                    array_push($updated, $achievementId);
1837                }
1838                $achievementId = 28;
1839                if ($acS['AchievementCondition']['value'] < 13 && !isset($existingAs[$achievementId])) {
1840                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1841                    ClassRegistry::init('AchievementStatus')->create();
1842                    ClassRegistry::init('AchievementStatus')->save($as);
1843                    array_push($updated, $achievementId);
1844                }
1845                $achievementId = 29;
1846                if ($acS['AchievementCondition']['value'] < 8 && !isset($existingAs[$achievementId])) {
1847                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1848                    ClassRegistry::init('AchievementStatus')->create();
1849                    ClassRegistry::init('AchievementStatus')->save($as);
1850                    array_push($updated, $achievementId);
1851                }
1852            } elseif ($s['Set']['difficulty'] >= 1500 && $s['Set']['difficulty'] < 1700) {
1853                $achievementId = 18;
1854                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
1855                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1856                    ClassRegistry::init('AchievementStatus')->create();
1857                    ClassRegistry::init('AchievementStatus')->save($as);
1858                    array_push($updated, $achievementId);
1859                }
1860                $achievementId = 19;
1861                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
1862                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1863                    ClassRegistry::init('AchievementStatus')->create();
1864                    ClassRegistry::init('AchievementStatus')->save($as);
1865                    array_push($updated, $achievementId);
1866                }
1867                $achievementId = 20;
1868                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
1869                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1870                    ClassRegistry::init('AchievementStatus')->create();
1871                    ClassRegistry::init('AchievementStatus')->save($as);
1872                    array_push($updated, $achievementId);
1873                }
1874                $achievementId = 30;
1875                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
1876                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1877                    ClassRegistry::init('AchievementStatus')->create();
1878                    ClassRegistry::init('AchievementStatus')->save($as);
1879                    array_push($updated, $achievementId);
1880                }
1881                $achievementId = 31;
1882                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
1883                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1884                    ClassRegistry::init('AchievementStatus')->create();
1885                    ClassRegistry::init('AchievementStatus')->save($as);
1886                    array_push($updated, $achievementId);
1887                }
1888                $achievementId = 32;
1889                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
1890                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1891                    ClassRegistry::init('AchievementStatus')->create();
1892                    ClassRegistry::init('AchievementStatus')->save($as);
1893                    array_push($updated, $achievementId);
1894                }
1895            } else {
1896                $achievementId = 21;
1897                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
1898                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1899                    ClassRegistry::init('AchievementStatus')->create();
1900                    ClassRegistry::init('AchievementStatus')->save($as);
1901                    array_push($updated, $achievementId);
1902                }
1903                $achievementId = 22;
1904                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
1905                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1906                    ClassRegistry::init('AchievementStatus')->create();
1907                    ClassRegistry::init('AchievementStatus')->save($as);
1908                    array_push($updated, $achievementId);
1909                }
1910                $achievementId = 23;
1911                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
1912                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1913                    ClassRegistry::init('AchievementStatus')->create();
1914                    ClassRegistry::init('AchievementStatus')->save($as);
1915                    array_push($updated, $achievementId);
1916                }
1917                $achievementId = 33;
1918                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
1919                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1920                    ClassRegistry::init('AchievementStatus')->create();
1921                    ClassRegistry::init('AchievementStatus')->save($as);
1922                    array_push($updated, $achievementId);
1923                }
1924                $achievementId = 34;
1925                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
1926                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1927                    ClassRegistry::init('AchievementStatus')->create();
1928                    ClassRegistry::init('AchievementStatus')->save($as);
1929                    array_push($updated, $achievementId);
1930                }
1931                $achievementId = 35;
1932                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
1933                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1934                    ClassRegistry::init('AchievementStatus')->create();
1935                    ClassRegistry::init('AchievementStatus')->save($as);
1936                    array_push($updated, $achievementId);
1937                }
1938            }
1939            $achievementId = 46;
1940            if ($acA['AchievementCondition']['value'] >= 100) {
1941                $ac100 = ClassRegistry::init('AchievementCondition')->find('all', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => '%', 'value >=' => 100]]);
1942                if (!$ac100) {
1943                    $ac100 = [];
1944                }
1945                $ac100counter = 0;
1946                $ac100Count = count($ac100);
1947                for ($j = 0; $j < $ac100Count; $j++) {
1948                    if (count(TsumegoUtil::collectTsumegosFromSet($ac100[$j]['AchievementCondition']['set_id'])) >= 100) {
1949                        $ac100counter++;
1950                    }
1951                }
1952                $as100 = ClassRegistry::init('AchievementStatus')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'achievement_id' => $achievementId]]);
1953                if ($as100 == null) {
1954                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1955                    $as['AchievementStatus']['value'] = 1;
1956                    ClassRegistry::init('AchievementStatus')->create();
1957                    ClassRegistry::init('AchievementStatus')->save($as);
1958                    array_push($updated, $achievementId);
1959                } elseif ($as100['AchievementStatus']['value'] != $ac100counter) {
1960                    $as100['AchievementStatus']['value'] = $ac100counter;
1961                    ClassRegistry::init('AchievementStatus')->save($as100);
1962                    array_push($updated, $achievementId);
1963                }
1964            }
1965        }
1966        $updatedCount = count($updated);
1967        for ($i = 0; $i < $updatedCount; $i++) {
1968            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1969            $updated[$i] = [];
1970            $updated[$i][0] = $a['Achievement']['name'];
1971            $updated[$i][1] = $a['Achievement']['description'];
1972            $updated[$i][2] = $a['Achievement']['image'];
1973            $updated[$i][3] = $a['Achievement']['color'];
1974            $updated[$i][4] = $a['Achievement']['xp'];
1975            $updated[$i][5] = $a['Achievement']['id'];
1976        }
1977
1978        return $updated;
1979    }
1980
1981    public static function updateXP($userID, $achievementData): void {
1982        $xpBonus = 0;
1983        $aCount = count($achievementData);
1984        for ($i = 0; $i < $aCount; $i++) {
1985            $xpBonus += $achievementData[$i][4];
1986        }
1987        if ($xpBonus == 0) {
1988            return;
1989        }
1990        $user = ClassRegistry::init('User')->findById($userID);
1991        $user['User']['xp'] = $xpBonus;
1992        Level::checkLevelUp($user['User']);
1993        ClassRegistry::init('User')->save($user);
1994    }
1995
1996    /**
1997     * @param int $uid User ID
1998     * @return void
1999     */
2000    protected function handleSearchSettings($uid) {
2001        $this->loadModel('UserContribution');
2002        $uc = $this->UserContribution->find('first', ['conditions' => ['user_id' => $uid]]);
2003        if ($uc == null) {
2004            $uc = [];
2005            $uc['UserContribution']['user_id'] = $uid;
2006            $uc['UserContribution']['added_tag'] = 0;
2007            $uc['UserContribution']['created_tag'] = 0;
2008            $uc['UserContribution']['made_proposal'] = 0;
2009            $uc['UserContribution']['reviewed'] = 0;
2010            $uc['UserContribution']['score'] = 0;
2011            $this->UserContribution->create();
2012            $this->UserContribution->save($uc);
2013        }
2014        new TsumegoFilters();
2015    }
2016
2017    protected function signIn(array $user): void {
2018        Auth::init($user);
2019        $vs = $this->TsumegoStatus->find('first', ['conditions' => ['user_id' => $user['User']['id']], 'order' => 'updated DESC']);
2020        if ($vs) {
2021            $this->Session->write('lastVisit', $vs['TsumegoStatus']['tsumego_id']);
2022        }
2023        $this->Session->write('texture', $user['User']['texture']);
2024        $this->Session->write('check1', $user['User']['id']);
2025    }
2026
2027    public function beforeFilter(): void {
2028        $this->loadModel('User');
2029        $this->loadModel('Activate');
2030        $this->loadModel('Tsumego');
2031        $this->loadModel('TsumegoRatingAttempt');
2032        $this->loadModel('Set');
2033        $this->loadModel('TimeModeAttempt');
2034        $this->loadModel('TsumegoStatus');
2035        $this->loadModel('Comment');
2036        $this->loadModel('TsumegoAttempt');
2037        $this->loadModel('AdminActivity');
2038        $this->loadModel('Achievement');
2039        $this->loadModel('AchievementStatus');
2040        $this->loadModel('AchievementCondition');
2041        $this->loadModel('SetConnection');
2042        $this->loadModel('Tag');
2043        $this->loadModel('TagName');
2044        $this->loadModel('Favorite');
2045
2046        Auth::init();
2047        $timeMode = new TimeMode();
2048
2049        $highscoreLink = 'highscore';
2050        $lightDark = 'light';
2051        $resetCookies = false;
2052        $levelBar = 1;
2053        $lastProfileLeft = 1;
2054        $lastProfileRight = 2;
2055        $hasFavs = false;
2056
2057        if (Auth::isLoggedIn()) {
2058            if (isset($_COOKIE['addTag']) && $_COOKIE['addTag'] != 0 && $this->Session->read('page') != 'set') {
2059                $newAddTag = explode('-', $_COOKIE['addTag']);
2060                $tagId = $newAddTag[0];
2061                $newTagName = $this->TagName->find('first', ['conditions' => ['name' => str_replace($tagId . '-', '', $_COOKIE['addTag'])]]);
2062                if ($newTagName) {
2063                    $saveTag = [];
2064                    $saveTag['Tag']['tag_name_id'] = $newTagName['TagName']['id'];
2065                    $saveTag['Tag']['tsumego_id'] = $tagId;
2066                    $saveTag['Tag']['user_id'] = Auth::getUserID();
2067                    $saveTag['Tag']['approved'] = 0;
2068                    $this->Tag->save($saveTag);
2069                }
2070                $this->set('removeCookie', 'addTag');
2071            }
2072            if (isset($_COOKIE['z_sess']) && $_COOKIE['z_sess'] != 0
2073            && strlen($_COOKIE['z_sess']) > 5) {
2074                Auth::getUser()['_sessid'] = $_COOKIE['z_sess'];
2075                Auth::saveUser();
2076            }
2077            if (Auth::getUser()['lastHighscore'] == 1) {
2078                $highscoreLink = 'highscore';
2079            } elseif (Auth::getUser()['lastHighscore'] == 2) {
2080                $highscoreLink = 'rating';
2081            } elseif (Auth::getUser()['lastHighscore'] == 3) {
2082                $highscoreLink = 'leaderboard';
2083            } elseif (Auth::getUser()['lastHighscore'] == 4) {
2084                $highscoreLink = 'highscore3';
2085            }
2086
2087            if (isset($_COOKIE['lastMode']) && $_COOKIE['lastMode'] != 0) {
2088                Auth::getUser()['lastMode'] = $_COOKIE['lastMode'];
2089                Auth::saveUser();
2090            }
2091            if (isset($_COOKIE['sound']) && $_COOKIE['sound'] != '0') {
2092                Auth::getUser()['sound'] = $_COOKIE['sound'];
2093                Auth::saveUser();
2094                unset($_COOKIE['sound']);
2095            }
2096            $this->set('ac', true);
2097            $this->set('user', Auth::getUser());
2098        }
2099
2100        if (isset($_COOKIE['lightDark']) && $_COOKIE['lightDark'] != '0') {
2101            $lightDark = $_COOKIE['lightDark'];
2102            if (Auth::isLoggedIn()) {
2103                // Convert string to integer for database storage
2104                $lightDarkInt = ($lightDark === 'light') ? 0 : 2;
2105                Auth::getUser()['lastLight'] = $lightDarkInt;
2106            }
2107        } elseif (Auth::isLoggedIn()) {
2108            if (Auth::getUser()['lastLight'] == 0
2109            || Auth::getUser()['lastLight'] == 1) {
2110                $lightDark = 'light';
2111            } else {
2112                $lightDark = 'dark';
2113            }
2114        }
2115
2116        if (Auth::isLoggedIn()) {
2117            $this->handleSearchSettings(Auth::getUserID());
2118            if (isset($_COOKIE['levelBar']) && $_COOKIE['levelBar'] != '0') {
2119                $levelBar = $_COOKIE['levelBar'];
2120                Auth::getUser()['levelBar'] = $levelBar;
2121            } elseif (Auth::getUser()['levelBar'] == 0
2122          || Auth::getUser()['levelBar'] == 'level') {
2123                $levelBar = 1;
2124            } else {
2125                $levelBar = 2;
2126            }
2127
2128            if (isset($_COOKIE['lastProfileLeft']) && $_COOKIE['lastProfileLeft'] != '0') {
2129                $lastProfileLeft = $_COOKIE['lastProfileLeft'];
2130                Auth::getUser()['lastProfileLeft'] = $lastProfileLeft;
2131            } else {
2132                $lastProfileLeft = Auth::getUser()['lastProfileLeft'];
2133                if ($lastProfileLeft == 0) {
2134                    $lastProfileLeft = 1;
2135                }
2136            }
2137            if (isset($_COOKIE['lastProfileRight']) && $_COOKIE['lastProfileRight'] != '0') {
2138                $lastProfileRight = $_COOKIE['lastProfileRight'];
2139                Auth::getUser()['lastProfileRight'] = $lastProfileRight;
2140            } else {
2141                $lastProfileRight = Auth::getUser()['lastProfileRight'];
2142                if ($lastProfileRight == 0) {
2143                    $lastProfileRight = 1;
2144                }
2145            }
2146        }
2147        $mode = 1;
2148        if (isset($_COOKIE['mode']) && $_COOKIE['mode'] != '0') {
2149            if ($_COOKIE['mode'] == 1) {
2150                $mode = 1;
2151            } else {
2152                $mode = 2;
2153            }
2154        }
2155
2156        if (Auth::isLoggedIn() && Auth::getUser()['mode'] == 2) {
2157            $mode = 2;
2158        }
2159
2160        if ($_COOKIE['sprint'] != 1) {
2161            $this->updateSprintCondition();
2162        }
2163
2164        if (Auth::isLoggedIn()) {
2165            if (isset($_COOKIE['revelation']) && $_COOKIE['revelation'] != 0) {
2166                Auth::getUser()['revelation'] -= 1;
2167            }
2168
2169            if (!$this->request->is('ajax')) {
2170                $this->PlayResultProcessor->checkPreviousPlay($timeMode);
2171            }
2172        }
2173        $boardNames = [];
2174        $enabledBoards = [];
2175        $boardPositions = [];
2176
2177        $boardNames[1] = 'Pine';
2178        $boardNames[2] = 'Ash';
2179        $boardNames[3] = 'Maple';
2180        $boardNames[4] = 'Shin Kaya';
2181        $boardNames[5] = 'Birch';
2182        $boardNames[6] = 'Wenge';
2183        $boardNames[7] = 'Walnut';
2184        $boardNames[8] = 'Mahogany';
2185        $boardNames[9] = 'Blackwood';
2186        $boardNames[10] = 'Marble 1';
2187        $boardNames[11] = 'Marble 2';
2188        $boardNames[12] = 'Marble 3';
2189        $boardNames[13] = 'Tibet Spruce';
2190        $boardNames[14] = 'Marble 4';
2191        $boardNames[15] = 'Marble 5';
2192        $boardNames[16] = 'Quarry 1';
2193        $boardNames[17] = 'Flowers';
2194        $boardNames[18] = 'Nova';
2195        $boardNames[19] = 'Spring';
2196        $boardNames[20] = 'Moon';
2197        $boardNames[21] = 'Apex';
2198        $boardNames[22] = 'Gold 1';
2199        $boardNames[23] = 'Amber';
2200        $boardNames[24] = 'Marble 6';
2201        $boardNames[25] = 'Marble 7';
2202        $boardNames[26] = 'Marble 8';
2203        $boardNames[27] = 'Marble 9';
2204        $boardNames[28] = 'Marble 10';
2205        $boardNames[29] = 'Jade';
2206        $boardNames[30] = 'Quarry 2';
2207        $boardNames[31] = 'Black Bricks';
2208        $boardNames[32] = 'Wallpaper 1';
2209        $boardNames[33] = 'Wallpaper 2';
2210        $boardNames[34] = 'Gold & Gray';
2211        $boardNames[35] = 'Gold & Pink';
2212        $boardNames[36] = 'Veil';
2213        $boardNames[37] = 'Tiles';
2214        $boardNames[38] = 'Mars';
2215        $boardNames[39] = 'Pink Cloud';
2216        $boardNames[40] = 'Reptile';
2217        $boardNames[41] = 'Mezmerizing';
2218        $boardNames[42] = 'Magenta Sky';
2219        $boardNames[43] = 'Tsumego Hero';
2220        $boardNames[44] = 'Pretty';
2221        $boardNames[45] = 'Hunting';
2222        $boardNames[46] = 'Haunted';
2223        $boardNames[47] = 'Carnage';
2224        $boardNames[48] = 'Blind Spot';
2225        $boardNames[49] = 'Giants';
2226        $boardNames[50] = 'Gems';
2227        $boardNames[51] = 'Grandmaster';
2228        $boardPositions[1] = [1, 'texture1', 'black34.png', 'white34.png'];
2229        $boardPositions[2] = [2, 'texture2', 'black34.png', 'white34.png'];
2230        $boardPositions[3] = [3, 'texture3', 'black34.png', 'white34.png'];
2231        $boardPositions[4] = [4, 'texture4', 'black.png', 'white.png'];
2232        $boardPositions[5] = [5, 'texture5', 'black34.png', 'white34.png'];
2233        $boardPositions[6] = [6, 'texture6', 'black.png', 'white.png'];
2234        $boardPositions[7] = [7, 'texture7', 'black34.png', 'white34.png'];
2235        $boardPositions[8] = [8, 'texture8', 'black.png', 'white.png'];
2236        $boardPositions[9] = [9, 'texture9', 'black.png', 'white.png'];
2237        $boardPositions[10] = [10, 'texture10', 'black34.png', 'white34.png'];
2238        $boardPositions[11] = [11, 'texture11', 'black34.png', 'white34.png'];
2239        $boardPositions[12] = [12, 'texture12', 'black34.png', 'white34.png'];
2240        $boardPositions[13] = [13, 'texture13', 'black34.png', 'white34.png'];
2241        $boardPositions[14] = [14, 'texture14', 'black34.png', 'white34.png'];
2242        $boardPositions[15] = [15, 'texture15', 'black.png', 'white.png'];
2243        $boardPositions[16] = [16, 'texture16', 'black34.png', 'white34.png'];
2244        $boardPositions[17] = [17, 'texture17', 'black34.png', 'white34.png'];
2245        $boardPositions[18] = [18, 'texture18', 'black.png', 'white.png'];
2246        $boardPositions[19] = [19, 'texture19', 'black34.png', 'white34.png'];
2247        $boardPositions[20] = [20, 'texture20', 'black34.png', 'white34.png'];
2248        $boardPositions[21] = [33, 'texture33', 'black34.png', 'white34.png'];
2249        $boardPositions[22] = [21, 'texture21', 'black.png', 'whiteKo.png'];
2250        $boardPositions[23] = [22, 'texture22', 'black34.png', 'white34.png'];
2251        $boardPositions[24] = [34, 'texture34', 'black.png', 'white.png'];
2252        $boardPositions[25] = [35, 'texture35', 'black34.png', 'white34.png'];
2253        $boardPositions[26] = [36, 'texture36', 'black.png', 'white.png'];
2254        $boardPositions[27] = [37, 'texture37', 'black34.png', 'white34.png'];
2255        $boardPositions[28] = [38, 'texture38', 'black38.png', 'white34.png'];
2256        $boardPositions[29] = [39, 'texture39', 'black.png', 'white.png'];
2257        $boardPositions[30] = [40, 'texture40', 'black34.png', 'white34.png'];
2258        $boardPositions[31] = [41, 'texture41', 'black34.png', 'white34.png'];
2259        $boardPositions[32] = [42, 'texture42', 'black34.png', 'white42.png'];
2260        $boardPositions[33] = [43, 'texture43', 'black34.png', 'white42.png'];
2261        $boardPositions[34] = [44, 'texture44', 'black34.png', 'white34.png'];
2262        $boardPositions[35] = [45, 'texture45', 'black34.png', 'white42.png'];
2263        $boardPositions[36] = [47, 'texture47', 'black34.png', 'white34.png'];
2264        $boardPositions[37] = [48, 'texture48', 'black34.png', 'white34.png'];
2265        $boardPositions[38] = [49, 'texture49', 'black.png', 'white.png'];
2266        $boardPositions[39] = [50, 'texture50', 'black34.png', 'white34.png'];
2267        $boardPositions[40] = [51, 'texture51', 'black34.png', 'white34.png'];
2268        $boardPositions[41] = [52, 'texture52', 'black34.png', 'white34.png'];
2269        $boardPositions[42] = [53, 'texture53', 'black34.png', 'white34.png'];
2270        $boardPositions[43] = [54, 'texture54', 'black54.png', 'white54.png'];
2271        $boardPositions[44] = [23, 'texture23', 'black.png', 'whiteFlower.png'];
2272        $boardPositions[45] = [24, 'texture24', 'black24.png', 'white24.png'];
2273        $boardPositions[46] = [25, 'texture25', 'blackGhost.png', 'white.png'];
2274        $boardPositions[47] = [26, 'texture26', 'blackInvis.png', 'whiteCarnage.png'];
2275        $boardPositions[48] = [27, 'texture27', 'black27.png', 'white27.png'];
2276        $boardPositions[49] = [28, 'texture28', 'blackGiant.png', 'whiteKo.png'];
2277        $boardPositions[50] = [29, 'texture29', 'blackKo.png', 'whiteKo.png'];
2278        $boardPositions[51] = [30, 'texture55', 'blackGalaxy.png', 'whiteGalaxy.png'];
2279
2280        $boardCount = 51;
2281
2282        if ($this->Session->check('texture') || (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0')) {
2283            $splitCookie = [];
2284            if (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0') {
2285                $splitCookie = str_split($_COOKIE['texture']);
2286                $textureCookies = $_COOKIE['texture'];
2287                Auth::getUser()['texture'] = $this->Session->read('texture');
2288                $this->Session->write('texture', $_COOKIE['texture']);
2289                $this->set('textureCookies', $textureCookies);
2290            } else {
2291                if (Auth::isLoggedIn()) {
2292                    $this->Session->write('texture', Auth::getUser()['texture']);
2293                }
2294                $textureCookies = $this->Session->read('texture');
2295                $splitTextureCookies = str_split($textureCookies);
2296                $splitTextureCookiesCount = count($splitTextureCookies);
2297                for ($i = 0; $i < $splitTextureCookiesCount; $i++) {
2298                    if ($splitTextureCookies[$i] == 2) {
2299                        $enabledBoards[$i + 1] = 'checked';
2300                    } else {
2301                        $enabledBoards[$i + 1] = '';
2302                    }
2303                }
2304            }
2305
2306            $splitCookieCount = count($splitCookie);
2307            for ($i = 0; $i < $splitCookieCount; $i++) {
2308                if ($splitCookie[$i] == 2) {
2309                    $enabledBoards[$i + 1] = 'checked';
2310                } else {
2311                    $enabledBoards[$i + 1] = '';
2312                }
2313            }
2314            if (Auth::isLoggedIn()) {
2315                Auth::saveUser();
2316            }
2317        }
2318
2319        if (!$this->Session->check('texture')) {
2320            $this->Session->write('texture', '222222221111111111111111111111111111111111111111111');
2321            $enabledBoards[1] = 'checked';
2322            $enabledBoards[2] = 'checked';
2323            $enabledBoards[3] = 'checked';
2324            $enabledBoards[4] = 'checked';
2325            $enabledBoards[5] = 'checked';
2326            $enabledBoards[6] = 'checked';
2327            $enabledBoards[7] = 'checked';
2328            $enabledBoards[8] = 'checked';
2329            $enabledBoards[9] = '';
2330            $enabledBoards[10] = '';
2331            $enabledBoards[11] = '';
2332            $enabledBoards[12] = '';
2333            $enabledBoards[13] = '';
2334            $enabledBoards[14] = '';
2335            $enabledBoards[15] = '';
2336            $enabledBoards[16] = '';
2337            $enabledBoards[17] = '';
2338            $enabledBoards[18] = '';
2339            $enabledBoards[19] = '';
2340            $enabledBoards[20] = '';
2341            $enabledBoards[21] = '';
2342            $enabledBoards[22] = '';
2343            $enabledBoards[23] = '';
2344            $enabledBoards[24] = '';
2345            $enabledBoards[25] = '';
2346            $enabledBoards[26] = '';
2347            $enabledBoards[27] = '';
2348            $enabledBoards[28] = '';
2349            $enabledBoards[29] = '';
2350            $enabledBoards[30] = '';
2351            $enabledBoards[31] = '';
2352            $enabledBoards[32] = '';
2353            $enabledBoards[33] = '';
2354            $enabledBoards[34] = '';
2355            $enabledBoards[35] = '';
2356            $enabledBoards[36] = '';
2357            $enabledBoards[37] = '';
2358            $enabledBoards[38] = '';
2359            $enabledBoards[39] = '';
2360            $enabledBoards[40] = '';
2361            $enabledBoards[41] = '';
2362            $enabledBoards[42] = '';
2363            $enabledBoards[43] = '';
2364            $enabledBoards[44] = '';
2365            $enabledBoards[45] = '';
2366            $enabledBoards[46] = '';
2367            $enabledBoards[47] = '';
2368            $enabledBoards[48] = '';
2369            $enabledBoards[49] = '';
2370            $enabledBoards[50] = '';
2371            $enabledBoards[51] = '';
2372        }
2373        $achievementUpdate = [];
2374        if ($this->Session->check('initialLoading')) {
2375            $achievementUpdate1 = $this->checkLevelAchievements();
2376            $achievementUpdate2 = $this->checkProblemNumberAchievements();
2377            $achievementUpdate3 = $this->checkRatingAchievements();
2378            $achievementUpdate4 = $this->checkTimeModeAchievements();
2379            $achievementUpdate5 = $this->checkDanSolveAchievements();
2380            $achievementUpdate = array_merge(
2381                $achievementUpdate1 ?: [],
2382                $achievementUpdate2 ?: [],
2383                $achievementUpdate3 ?: [],
2384                $achievementUpdate4 ?: [],
2385                $achievementUpdate5 ?: []
2386            );
2387            $this->Session->delete('initialLoading');
2388        }
2389
2390        if (count($achievementUpdate) > 0) {
2391            $this->updateXP(Auth::getUserID(), $achievementUpdate);
2392        }
2393
2394        $nextDay = new DateTime('tomorrow');
2395        if (Auth::isLoggedIn()) {
2396            Auth::getUser()['name'] = $this->checkPicture(Auth::getUser());
2397            $this->set('user', Auth::getUser());
2398        }
2399        $this->set('mode', $mode);
2400        $this->set('nextDay', $nextDay->format('m/d/Y'));
2401        $this->set('boardNames', $boardNames);
2402        $this->set('enabledBoards', $enabledBoards);
2403        $this->set('boardPositions', $boardPositions);
2404        $this->set('highscoreLink', $highscoreLink);
2405        $this->set('achievementUpdate', $achievementUpdate);
2406        $this->set('lightDark', $lightDark);
2407        $this->set('levelBar', $levelBar);
2408        $this->set('lastProfileLeft', $lastProfileLeft);
2409        $this->set('lastProfileRight', $lastProfileRight);
2410        $this->set('resetCookies', $resetCookies);
2411        $this->set('hasFavs', $hasFavs);
2412    }
2413
2414    public function afterFilter() {}
2415}